Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 289
user3602239 Avatar asked Jun 21 '14 22:06

user3602239


People also ask

How do I combine 3 strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you concatenate 3 strings in Python?

To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.

How do I concatenate strings multiple times?

Dart – Concatenate a String with itself Multiple Times To concatenate a string with itself multiple times in Dart, use Multiplication Operator * and pass the string and the integer as operands to it.


2 Answers

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

like image 63
Ben Bolker Avatar answered Sep 24 '22 08:09

Ben Bolker


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.

like image 34
Arun Avatar answered Sep 21 '22 08:09

Arun