我有这样的矢量:
test <- c("a","b","c","d")
test
[1] "a" "b" "c" "d"
我想粘贴一个字符串,例如“_2”,在向量的每个其他元素上,得到这个:
"a" "b_2" "c" "d_2"
我试过这个命令:
ifelse(test %in% seq(1, length(test), 2), test, paste(test, "_2", sep=""))
但这只是给了我:
"a_2" "b_2" "c_2" "d_2"
这是错误的。有关如何正确执行此操作的任何建议?谢谢!
答案 0 :(得分:6)
怎么样
paste0(c("a","b","c","d"), c("", "_2"))
[1] "a" "b_2" "c" "d_2"
答案 1 :(得分:2)
另一种选择是,
test[c(FALSE, TRUE)] <- paste0(test[c(FALSE, TRUE)], '_2')
test
#[1] "a" "b_2" "c" "d_2"
答案 2 :(得分:1)
x <- c("a","b","c","d")
x[seq(2, length(x), by=2)] <- paste0(x[seq(2, length(x), by=2)], "_2")
x
这给出了:
"a" "b_2" "c" "d_2"