如何交替连接3个字符串

我有3个字符串:

a<-c("a1","a2","a3")
b<-c("b1","b2","b3")
c<-c("c1","c2","c3")

我怎样才能得到以下输出:

"a1","b1","c1","a2","b2","c2","a3","b3","c3"

这是我试过的:

paste(a,b,c,sep='","')

我得到了什么:

[1] "a1","b1","c1" "a2","b2","c2" "a3","b3","c3"

有没有办法做到这一点? 谢谢。


你也可以使用

c(rbind(a,b,c))

rbindrbind三个变量放在一个矩阵中(row-wise),然后( c() )将它们转换回一个向量,利用R按矩阵顺序存储矩阵的事实。

在这个问题的答案中,一些多样性(我认为)是由于OP部分缺乏清晰性(不知道这是一个理解还是沟通的问题......),在组合单个字符串(例如paste("a","b")导致长度为1的矢量: "ab") )并且组合字符串的矢量( c("a","b")导致长度为2的矢量: "a" "b"


我会这样做:

interleave <- function(...) {
    ll <- list(...)
    unlist(ll)[order(unlist(lapply(ll, seq_along)))]
}
interleave(a,b,c)
# [1] "a1" "b1" "c1" "a2" "b2" "c2" "a3" "b3" "c3"

优点是你不必依赖于具有相同大小的矢量。 例如:

a <- paste("a", 1:3, sep="")
b <- paste("b", 1:4, sep="")
c <- paste("c", 1:5, sep="")

interleave(a,b,c)
# [1] "a1" "b1" "c1" "a2" "b2" "c2" "a3" "b3" "c3" "b4" "c4" "c5"

这与这个答案密切相关。


我认为这可能工作:

a<-c("a1","a2","a3")
b<-c("b1","b2","b3")
c<-c("c1","c2","c3")

c(sapply(seq(1,3), function(x) c(a[x],b[x],c[x])))

[1] "a1" "b1" "c1" "a2" "b2" "c2" "a3" "b3" "c3"
链接地址: http://www.djcxy.com/p/24847.html

上一篇: how to alternatively concatenate 3 strings

下一篇: Boxplot for each individual level in two factor columns?