Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pairs the elements of two vectors in R

Tags:

r

I would like to pair elements of two vectors in R. The order is important.

For example, 

    X= c(1:3)
    Y= c(1:3)
I expect to have:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3 

I would like to use 'lapply'. My data is more complicated but the idea is the same. I just need to pair each element of the first vector with all element of the second vector.


1 Answers

If "order is important" means that the "monotonic increase" is important, then simply

expand.grid(X, Y)
#   Var1 Var2
# 1    1    1
# 2    2    1
# 3    3    1
# 4    1    2
# 5    2    2
# 6    3    2
# 7    1    3
# 8    2    3
# 9    3    3

However, if column-order (second column increments before first), then just reverse the order of arguments (inferring that the real problem has differing numbers) and reorder them post-function:

expand.grid(Y, X)[2:1]
#   Var2 Var1
# 1    1    1
# 2    1    2
# 3    1    3
# 4    2    1
# 5    2    2
# 6    2    3
# 7    3    1
# 8    3    2
# 9    3    3

The column names are inferred from the arguments, so expand.grid(X=X, Y=Y) will name them X and Y instead of Var#.

like image 79
r2evans Avatar answered Sep 16 '25 04:09

r2evans