Pasting two vectors with combinations of all vectors' elements

DSSS picture DSSS · Apr 22, 2013 · Viewed 40.7k times · Source

I have two vectors:

vars <- c("SR", "PL")
vis <- c(1,2,3)

Based on these vectors I would like to create the following vector:

"SR.1"  "SR.2"  "SR.3"  "PL.1"  "PL.2"  "PL.3"

With paste I have the following result:

paste(vars, vis, sep=".")
 [1] "SR.1" "PL.2" "SR.3"

How can I create the vector I need?

Answer

juba picture juba · Apr 22, 2013

You can use this, but there may be a simpler solution :

R> apply(expand.grid(vars, vis), 1, paste, collapse=".")
[1] "SR.1" "PL.1" "SR.2" "PL.2" "SR.3" "PL.3"

expand.grid gives back a data.frame which when used with apply, apply will convert it to a matrix. This is just unnecessary (and inefficient on large data). outer gives a matrix and also takes function argument. It'll be much efficient on huge data as well.

Using outer:

as.vector(outer(vars, vis, paste, sep="."))
# [1] "SR.1" "PL.1" "SR.2" "PL.2" "SR.3" "PL.3"