combn() with fixed columns

The below code gives me all 4 column combinations of the iris data frame. How do get all combinations containing Species and 3 other columns? In other words would it be possible to fix certain columns in all combination results?

iris <- head(iris, 5)
iris
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa

combn(iris, 4, simplify = FALSE)

#> [[1]]
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1          5.1         3.5          1.4         0.2
#> 2          4.9         3.0          1.4         0.2
#> 3          4.7         3.2          1.3         0.2
#> 4          4.6         3.1          1.5         0.2
#> 5          5.0         3.6          1.4         0.2
#> 
#> [[2]]
#>   Sepal.Length Sepal.Width Petal.Length Species
#> 1          5.1         3.5          1.4  setosa
#> 2          4.9         3.0          1.4  setosa
#> 3          4.7         3.2          1.3  setosa
#> 4          4.6         3.1          1.5  setosa
#> 5          5.0         3.6          1.4  setosa
#> 
#> [[3]]
#>   Sepal.Length Sepal.Width Petal.Width Species
#> 1          5.1         3.5         0.2  setosa
#> 2          4.9         3.0         0.2  setosa
#> 3          4.7         3.2         0.2  setosa
#> 4          4.6         3.1         0.2  setosa
#> 5          5.0         3.6         0.2  setosa
#> 
#> [[4]]
#>   Sepal.Length Petal.Length Petal.Width Species
#> 1          5.1          1.4         0.2  setosa
#> 2          4.9          1.4         0.2  setosa
#> 3          4.7          1.3         0.2  setosa
#> 4          4.6          1.5         0.2  setosa
#> 5          5.0          1.4         0.2  setosa
#> 
#> [[5]]
#>   Sepal.Width Petal.Length Petal.Width Species
#> 1         3.5          1.4         0.2  setosa
#> 2         3.0          1.4         0.2  setosa
#> 3         3.2          1.3         0.2  setosa
#> 4         3.1          1.5         0.2  setosa
#> 5         3.6          1.4         0.2  setosa

Created on 2021-08-11 by the reprex package (v2.0.0)

Hi,

Here is a way to do that

#List all other columns
other = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")

#Get their combinations
myData = combn(other, 3, simplify = F)

#Add species to it
myData = lapply(myData, function(x) c("Species", x))

#Subset the data frame for each combinatiion
myData = lapply(myData, function(x){
  iris[,x]
})

Hope this helps,
PJ

1 Like

Thank you very much!

1 Like

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.