简体   繁体   中英

Create dataframe of all combinations of a list

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM