如何以指定的顺序连接字符串

时间:2014-06-22 12:56:41

标签: r concatenation

试图从这篇帖子how to alternatively concatenate 3 strings对角连接字符串,但没有成功。

我的意见是:

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

我的预期输出是

   "a1" "b2" "c3" "a2" "b3" "a3"

如何从

获得上述内容
  c(rbind(a,b,c))  

2 个答案:

答案 0 :(得分:8)

如何在将下对角线设置为缺失

之后按行和列导出的值对矢量进行排序
mat <- rbind(a,b,c)

mat[lower.tri(mat)] <- NA
na.omit(mat[order(col(mat) - row(mat))])

答案 1 :(得分:2)

一种方法是调整Mark's解决方案

as.vector(na.omit(c(sapply(1:3, function(i) c(a[i], b[i+1], c[i+2])))))
#[1] "a1" "b2" "c3" "a2" "b3" "a3"

此外,

 vec1 <- c(a,b,c)
 indx <- seq(1,length(vec1), by=4)+rep(0:2,each=3)
 indx1 <- indx[indx <= length(vec1)]
 vec1[indx1[-length(indx1)]]
 #[1] "a1" "b2" "c3" "a2" "b3" "a3"