Pasting two vectors with combinations of all vectors' elements
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?
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"
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
.
Another option using sprintf
in combination with expand.grid
:
eg <- expand.grid(vis, vars)
sprintf('%s.%s', eg[,2], eg[,1])
which gives:
[1] "SR.1" "SR.2" "SR.3" "PL.1" "PL.2" "PL.3"
Explanation:
- With
expand.grid
you create all combinations of the two vectors. -
sprintf
pastes the two vectors together according to the specified format ('%s.%s'
). Each%s
part of the format is replaced by the elements of the vectors.