更改R中字符串的前两个字符
Change first two characters in string in R
在 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"
尝试
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"
@grrgrrbla 谢谢,但就我而言,这不合适。
我已经从数值转换中逃脱,因为转换为数值变量时省略了 0。另一个例子是 0* hours
> 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"
这些字符给需要使用时间格式的地方加上冒号(h:m:s)和“0”带来了麻烦。
在 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"
尝试
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"
@grrgrrbla 谢谢,但就我而言,这不合适。 我已经从数值转换中逃脱,因为转换为数值变量时省略了 0。另一个例子是 0* hours
> 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"
这些字符给需要使用时间格式的地方加上冒号(h:m:s)和“0”带来了麻烦。