[英]Create dataframe of all combinations of a list
我有从 1 到 900 的整数数据框。
nodelist <- data.frame(node_id=seq(1:900))
我想创建一个包含矢量节点列表的每个组合的两列(顶部、底部)的新数据框。 顶部和底部的数字不能相同。 就像是:
top bottom
1 2
1 3
1 4
2 1
2 3
我试过 cross() 和 expand.grid() 无济于事。
我们可以使用expand.grid
并删除两列具有相同值的行。
nodelist <- data.frame(node_id=1:9)
subset(expand.grid(nodelist$node_id, nodelist$node_id), Var1 != Var2)
# Var1 Var2
#2 2 1
#3 3 1
#4 4 1
#5 5 1
#6 6 1
#7 7 1
#8 8 1
#9 9 1
#10 1 2
#...
#...
或与crossing
library(dplyr)
library(tidyr)
crossing(setNames(nodelist, 'top'), setNames(nodelist, 'bottom')) %>%
filter(top != bottom)
这是一次从向量中删除一个元素的选项:
nodelist <- seq(1:4)
data.frame(
top=rep(nodelist, each=length(nodelist) - 1L),
bottom=c(sapply(seq_along(nodelist), function(i) nodelist[-i]))
)
输出:
top bottom
1 1 2
2 1 3
3 1 4
4 2 1
5 2 3
6 2 4
7 3 1
8 3 2
9 3 4
10 4 1
11 4 2
12 4 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.