Pairwise combinations of variables into data frames

Hi,

I have 15 variables in a data frame. Of these I want to make data frames that consists of two variables in each frame, for all pairwise combinations of variables. I have not found a way to do that. Would be happy if I could get a clue...

I have tried using the combn() function, but it only combines the names of the variables.

Many thanks!

Here is one method.

DF <- data.frame(A = 1:4, B= 2:5, C = 3:6)
NamePairs <- combn(names(DF), 2)
OutList <- vector("list", length = ncol(NamePairs))
for (i in 1:ncol(NamePairs)) {
  OutList[[i]] <- DF[, NamePairs[,i]]
}
OutList
#> [[1]]
#>   A B
#> 1 1 2
#> 2 2 3
#> 3 3 4
#> 4 4 5
#> 
#> [[2]]
#>   A C
#> 1 1 3
#> 2 2 4
#> 3 3 5
#> 4 4 6
#> 
#> [[3]]
#>   B C
#> 1 2 3
#> 2 3 4
#> 3 4 5
#> 4 5 6

Created on 2023-05-27 with reprex v2.0.2

That is great! Thank you for the solution. I was just gonna post an example of what I meant:

df <- cbind(a = c(1, 2, 3), b = c(4, 5, 6), c = c(7, 8, 9))

df1 <- cbind(a = c(1, 2, 3), b = c(4, 5, 6))
df2 <- cbind(a = c(1, 2, 3), c = c(7, 8, 9))
df3 <- cbind(b = c(4, 5, 6), c = c(7, 8, 9))

list(df1, df2, df3)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.