Find All Possible Subsets of Vector Elements in R (Example Code)

In this article, I’ll explain how to identify all possible subsets of elements in a vector in the R programming language.

Creating Example Data

x <- paste0("X", 1:4)                  # Constructing vector in R
x                                      # Displaying example vector in RStudio console
# [1] "X1" "X2" "X3" "X4"

Example: Identify All Possible Subsets

install.packages("combinat")           # Install combinat package
library("combinat")                    # Load combinat package
x_sub <- unlist(lapply(1:length(x),    # Applying combn() function
                       combinat::combn, 
                       x = x,
                       simplify = FALSE), 
                recursive = FALSE)
x_sub                                  # Returning all subsets as list
# [[1]]
# [1] "X1"
# 
# [[2]]
# [1] "X2"
# 
# [[3]]
# [1] "X3"
# 
# [[4]]
# [1] "X4"
# 
# [[5]]
# [1] "X1" "X2"
# 
# [[6]]
# [1] "X1" "X3"
# 
# [[7]]
# [1] "X1" "X4"
# 
# [[8]]
# [1] "X2" "X3"
# 
# [[9]]
# [1] "X2" "X4"
# 
# [[10]]
# [1] "X3" "X4"
# 
# [[11]]
# [1] "X1" "X2" "X3"
# 
# [[12]]
# [1] "X1" "X2" "X4"
# 
# [[13]]
# [1] "X1" "X3" "X4"
# 
# [[14]]
# [1] "X2" "X3" "X4"
# 
# [[15]]
# [1] "X1" "X2" "X3" "X4"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top