在R中,我想找到并替换字符串中的两个字符(只是前两个字符) 这是我开始的数据。
time <- c("153500", "153800", "161400", "161700", "163000", "161800",
"201700", "201800")
from <- c("15", "16", "17", "18")
to <- c("10","11", "12", "13" )
repl <- data.frame(from, to)
结果应如下所示:
[1] "103500" "103800" "111400" "111700" "113000" "111800" "201700" "201800"
答案 0 :(得分:1)
尝试
v1 <- setNames(to, from)[substr(time, 1, 2)]
as.character(ifelse(!is.na(v1), paste0(v1, sub('^.{2}','', time)), time))
#[1] "103500" "103800" "111400" "111700" "113000" "111800" "201700" "201800"
答案 1 :(得分:0)
@grrgrrbla谢谢,但在我看来这不合适。 我已经从数值转换原因转换为数值变量省略了0.另一个例子是0 *小时
> time <- c("053500", "053800", "061400", "061700", "163000", "161800", "201700", "201800")
> from <- c("05", "06", "16", "20")
> test[substr(time, 1, 2) %in% from] <-
+ as.character(as.numeric(time[substr(time, 1, 2) %in% from]) - 50000)
> cbind(time, test)
time test
[1,] "053500" "3500"
[2,] "053800" "3800"
[3,] "061400" "11400"
[4,] "061700" "11700"
[5,] "163000" "113000"
[6,] "161800" "111800"
[7,] "201700" "151700"
[8,] "201800" "151800"
&#13;
这些字符很难添加冒号(h:m:s)和&#34; 0&#34;需要使用时间格式的地方。