0

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?

2
  • What's wrong with paste? Commented Jun 8, 2017 at 21:30
  • They all should have space. I've edited my question. Commented Jun 8, 2017 at 21:30

3 Answers 3

3
c(outer(a, b, paste))

# [1] "a 1" "b 1" "c 1" "a 2" "b 2" "c 2" "a 3" "b 3" "c 3"
Sign up to request clarification or add additional context in comments.

1 Comment

outer FTW ! I always forget that function :)
2

Other options are :

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

or :

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.