Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pasting two vectors with combinations of all vectors' elements

Tags:

r

r-faq

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?

like image 511
DSSS Avatar asked Apr 22 '13 09:04

DSSS


2 Answers

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" 
like image 128
juba Avatar answered Sep 28 '22 15:09

juba


Another option is to use the each argument of rep:

paste(rep(vars, each = length(vis)), vis, sep = ".") 

I find this more straightforward than the solutions based on apply or expand.grid.

like image 36
ewancarr Avatar answered Sep 28 '22 15:09

ewancarr