R 将字符串向量与 seq_len

R combine a vector of strings with seq_len

如果我有一个字符串列表,xyz。我希望将它们与 seq_len 结合起来,因此列表将变为:x1,y1,z1,x2,y2,z2,x3,y3,z3。我怎样才能做到这一点?我试过使用粘贴,但显然不起作用。谢谢。

a1 = c("x","y","z")
seq_len(3)

paste(a1, seq_len(3))

尝试outer

> c(outer(a1, seq_len(3), paste0))
[1] "x1" "y1" "z1" "x2" "y2" "z2" "x3" "y3" "z3"

sapply

> c(t(sapply(a1,paste0,seq_len(3))))
[1] "x1" "y1" "z1" "x2" "y2" "z2" "x3" "y3" "z3"
paste0(a1, rep(seq_len(3), each = 3))
# [1] "x1" "y1" "z1" "x2" "y2" "z2" "x3" "y3" "z3"

如果您打算直接使用 3 而不是从 al 序列中检索它,有一个简单的答案:

paste0(a1, gl(3, 3))
# "x1" "y1" "z1" "x2" "y2" "z2" "x3" "y3" "z3"

使用 expand.gridpaste

do.call(paste0, expand.grid(a1, seq_along(a1)))