假设我们有以下简化向量(实际上,它们包含更多值):
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
最佳答案
您可以组合需要组合在一起的对的列表,然后在 expand.grid
expand.grid(n, Map(c, x, y)) %>% tidyr::unnest_wider(Var2)
或者我们也可以使用相同的逻辑来使用交叉
。
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
关于r - R 中具有相同位置索引的向量值的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60200639/