【发布时间】:2015-05-06 03:23:45
【问题描述】:
如果满足条件,我想将 x 中字符串的第一个元素替换为空白:如果 x 中“101”的第一个元素与 y 中的第一个字符串匹配,则将“101”的第一个元素替换为空白。
x = c("101", "201", "301")
y = c("1", "7", "3")
想要:
> x
[1] "01" "201" "01"
我在尝试:
> ifelse(substr(x, 1, 1) == y, sub(substr(x, 1, 1), ""), x)
虽然不直观,但我知道这是错误的 - sub 需要一个模式作为第一个参数并且不会采用 substr。
也试过了:
> ifelse(substr(x, 1, 1) == y, substr(x, 1, 1) <- "", x)
[1] "" "201" ""
我提到了这个R: How can I replace let's say the 5th element within a string? 并使用以下方法解决了它:
ifelse(substr(x, 1, 1) == y, paste(substr(x, 2, nchar(x))), x)
想知道是否有更好的方法来做到这一点?
【问题讨论】: