How to concatenate strings in a specified order

自古美人都是妖i 提交于 2019-12-23 21:07:30

问题


Tried to concatenate strings diagonally from this post how to alternatively concatenate 3 strings, but was not successful.

My input is:

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

My expected output would be

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

How to get the above from

  c(rbind(a,b,c))  

回答1:


How about ordering the vector by values derived by the row and columns after setting the lower diagonal to missing

mat <- rbind(a,b,c)

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



回答2:


One way would be to tweak Mark's solution

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"

Also,

 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"


来源:https://stackoverflow.com/questions/24351451/how-to-concatenate-strings-in-a-specified-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!