Ran Tao
Ran Tao

Reputation: 311

concatenate two lists of string in r

Here is my sample:

a = c("a","b","c")
b = c("1","2","3")

I need to concatenate a and b automatically. The result should be "a 1","a 2","a 3","b 1","b 2","b 3","c 1","c 2","c 3".

For now, I am using the paste function:

paste(a[1],b[1])

I need an automatic way to do this. Besides writing a loop, is there any easier way to achieve this?

Upvotes: 0

Views: 340

Answers (3)

JasonWang
JasonWang

Reputation: 2434

c(outer(a, b, paste))

# [1] "a 1" "b 1" "c 1" "a 2" "b 2" "c 2" "a 3" "b 3" "c 3"

Upvotes: 3

digEmAll
digEmAll

Reputation: 57210

Other options are :

paste(rep.int(a,length(b)),b)

or :

with(expand.grid(b,a),paste(Var2,Var1))

Upvotes: 2

Bea
Bea

Reputation: 1110

You can do:

c(sapply(a, function(x) {paste(x,b)}))
[1] "a 1" "a 2" "a 3" "b 1" "b 2" "b 3" "c 1" "c 2" "c 3"

edited paste0 into paste to match OP update

Upvotes: 2

Related Questions