简体   繁体   中英

How to pairs the elements of two vectors in 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.

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# .

In tidyverse , we can use expand_grid

library(tidyr)
expand_grid(Y, X)

Or use crossing

crossing(X, Y)

Another base R option is outer (but not as straightforward as expand.grid )

> do.call(rbind, c(t(outer(X, Y, Vectorize(function(x, y) list(c(x, y)))))))
      [,1] [,2]
 [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

Or we can use lapply like below

> unname(do.call(rbind, lapply(X, cbind, Y)))
      [,1] [,2]
 [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

Here is a data table solution:

library(data.table)
CJ(X, Y, unique = TRUE)

Output:

   X Y
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM