r - 向量值与 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
解决方案
您可以组合需要在一起的对列表,然后在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
推荐阅读
- kubernetes - k3d 负载均衡器类型的服务没有外部 IP
- java - 使用自定义对象填充微调器。如何在自定义对象中设置微调器提示
- java - Tomcat中rest api的客户端身份验证
- python - 在使用递归的多重嵌套 for 循环的程序中找不到故障
- aws-lambda - 动态 Access-Control-Allow-Origin 标头无服务器
- python - 将 PDF 解析为 CSV
- javascript - 我如何使用 forEach 循环遍历这个
- python - 邮件合并值而不是使用 Python 的公式
- ubuntu - 错误未知/不支持的存储引擎:InnoDB
- javascript - 将 17 位数字字符串转换为整数