R:将矢量插入到字符串的每个其他字符中

时间:2015-07-19 21:45:02

标签: r string

假设您有一个字符串和一个长度相同的向量:

require(stringi)

string <- "ABCDEFGHIJKLMN"
vector <- 1:stri_length(string)

输出此内容的快速方法是什么?

# A1B2C3D4E5F6G7H8I9J10K11L12M13N14

或者输出一个看起来像这样的矢量(如果更简单):

vector2
# "A" "1" "B" "2" "C" "3" "D" "4" ........

1 个答案:

答案 0 :(得分:2)

可能有更好的方法,但这是我的尝试

paste(c(rbind(strsplit(string, "")[[1]], vector)), collapse = "")
## [1] "A1B2C3D4E5F6G7H8I9J10K11L12M13N14"

如果您想要第二个输出,只需删除

中的paste部分即可
c(rbind(strsplit(string, "")[[1]], vector))
#  [1] "A"  "1"  "B"  "2"  "C"  "3"  "D"  "4"  "E"  "5"  "F"  "6"  "G"  "7"  "H"  "8"  "I"  "9"  "J"  "10"
# [21] "K"  "11" "L"  "12" "M"  "13" "N"  "14"