r - Convert strings representing unit of time or distance to numeric -
i search data.frame column string distances , convert them numeric fields. same on twitter style dates such '3 days ago' using same function.
if starting with:
x <- c("5 days ago", "1 day ago", "6 days ago")
i end with:
x <- c(120, 24, 144)
any appreciated!
if data consist "number days ago" or "number miles" can use regular expressions:
> x <- c("5 days ago", "1 day ago", "6 days ago", "21.2 miles", "1 mile") > x[grep(" day",x)] <- as.numeric(gsub("[ daysago]","",x[grep(" day",x)] ))*24 > x [1] "120" "24" "144" "21.2 miles" "1 mile" > x[grep(" mile",x)] <- as.numeric(gsub("[ miles]","",x[grep(" mile",x)] )) > x [1] "120" "24" "144" "21.2" "1" > x <- as.numeric(x) > x [1] 120.0 24.0 144.0 21.2 1.0
Comments
Post a Comment