首页 > 解决方案 > 向量值与 R 中相同位置索引的组合

问题描述

假设我们有以下简化的向量(实际上,它们包含更多的值):

n <- c(1,2)
x <- c(4,5,6) 
y <- c(7,8,9)

#to get all possible combinations, we can use expand.grid 
df <- expand.grid(n=n,
                  x=x,
                  y=y
)

> df
   n x y
   1 4 7
   2 4 7
   1 5 7
   2 5 7
   1 6 7
   2 6 7
   1 4 8
   2 4 8
   1 5 8
   2 5 8
   1 6 8
   2 6 8
   1 4 9
   2 4 9
   1 5 9
   2 5 9
   1 6 9
   2 6 9

但是,我希望向量x , y具有仅考虑具有相同索引值的元素的组合,即 (x1, y1), (x2, y2), (x3, y3) 但不是 (x1,y2), (x1,y3) 等,而向量n仍然照常使用(它的所有元素都与 x 和 y 组合的结果“配对”)。

换句话说,我想得到以下df:  

   n x y
   1 4 7
   2 4 7
   1 5 8
   2 5 8
   1 6 9
   2 6 9

如果n向量有 3 个元素,即 n <- (1, 2, 3),那么我们将有:

   n x y
   1 4 7
   2 4 7
   3 4 7
   1 5 8
   2 5 8
   3 5 8
   1 6 9
   2 6 9
   3 6 9

标签: r

解决方案


您可以组合需要在一起的对列表,然后在expand.grid

expand.grid(n, Map(c, x, y)) %>% tidyr::unnest_wider(Var2)

或者我们也可以crossing使用相同的逻辑。

library(tidyverse)

crossing(n, x = map2(x, y, c)) %>%
  unnest_wider(x) %>%
  rename_at(-1, ~c("x", "y"))

#      n     x     y
#  <dbl> <dbl> <dbl>
#1     1     4     7
#2     1     5     8
#3     1     6     9
#4     2     4     7
#5     2     5     8
#6     2     6     9

推荐阅读