how to alternatively concatenate 3 strings

懵懂的女人 提交于 2019-12-12 10:56:29

问题


I have 3 strings:

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

How can I get the following output:

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

Here is what I tried:

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

And what I got:

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

Is there a way to do it? Thank you.


回答1:


You could also use

c(rbind(a,b,c))

which (rbind) puts the three variables together into a matrix (row-wise), and then (c()) converts them back into a vector, taking advantage of the fact that R stores matrices in column-wise order.

Some of the diversity of the answers to this question stems (I think) from a lack of clarity on the OP's part (don't know whether this is an issue of understanding or communication ...) between combining individual character strings (e.g. paste("a","b") results in a vector of length 1: "a b")) and combining vectors of character strings (c("a","b") results in a vector of length 2: "a" "b")




回答2:


I'd do it this way:

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"

The advantage is that you don't have to depend on the vectors having the same size. For example:

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"

This is closely related to this answer.




回答3:


I think this might work:

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"



回答4:


You could use grep to put them in the order you want

> x <- c(a, b, c)
> x[sapply(1:3, grep, x)]
# [1] "a1" "b1" "c1" "a2" "b2" "c2" "a3" "b3" "c3" 

or unlist(strsplit(paste(a, b, c), " ")) would work too.

Although, it seems like you may be trying to paste commas in there. If that's what you're shooting for, try using cat with the sep argument set to ","

> cat(x[sapply(1:3, grep, x)], sep = ",")
# a1,b1,c1,a2,b2,c2,a3,b3,c3  

or perhaps paste, but with both the sep and collapse arguments set to ","

> paste(a, b, c, sep = ",", collapse = ",")
# [1] "a1,b1,c1,a2,b2,c2,a3,b3,c3" 



回答5:


I think what you want is:

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

You don't need double quotes to get the ",". The inner paste() does what you tried then the outer paste() joins these all together to give you the output you want. Don't worry about the output having "\" in it - if you print it out with cat, you'll see them disappear.

Does that work for you?



来源:https://stackoverflow.com/questions/24346355/how-to-alternatively-concatenate-3-strings

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