Reputation: 363
I have dataframe of integers from 1 to 900.
nodelist <- data.frame(node_id=seq(1:900))
I want to create a new dataframe of two columns (top, bottom) that has each combination of the vector nodelist. The top and bottom number cannot be the same. Something like:
top bottom
1 2
1 3
1 4
2 1
2 3
I have tried cross() and expand.grid() to no avail.
Upvotes: 0
Views: 649
Reputation: 388817
We can use expand.grid
and remove the rows where two columns have same values.
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
#...
#...
Or with crossing
library(dplyr)
library(tidyr)
crossing(setNames(nodelist, 'top'), setNames(nodelist, 'bottom')) %>%
filter(top != bottom)
Upvotes: 3
Reputation: 25225
Here is an option by removing one element from the vector one at a time:
nodelist <- seq(1:4)
data.frame(
top=rep(nodelist, each=length(nodelist) - 1L),
bottom=c(sapply(seq_along(nodelist), function(i) nodelist[-i]))
)
output:
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
Upvotes: 0