Wednesday 18 September 2019

r - how to alternatively concatenate 3 strings



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.



Answer



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")


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...