我想搜索带有字符串距离的data.frame列并将它们转换为数字字段。我会在推特风格的日期,例如'3天前'使用相同的功能。
如果我开始时:
x <- c("5 days ago", "1 day ago", "6 days ago")
我最终会:
x <- c(120, 24, 144)
任何帮助将不胜感激!
答案 0 :(得分:1)
检查stringr
库和str_extract_all
功能
x <- c("5 days ago", "1 day ago", "6 days ago")
library(stringr)
x <- 24*as.numeric(str_extract_all(x, "\\d"))
答案 1 :(得分:0)
试试这个:
strLine <- c("5 days ago", "1 day ago", "6 days ago")
x <- as.numeric(unlist(regmatches(strLine, gregexpr('\\(?[0-9]+', strLine)))) * 24
x
# [1] 120 24 144
答案 2 :(得分:0)
如果您的数据仅包含&#34;数天前&#34;或者&#34;里程数&#34;你可以使用正则表达式:
> 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