Generate All Combinations of n Elements in R | /cn/2007/04/generate-all-combinations-of-n-elements-in-r/
Generate All Combinations of n Elements in R
https://yihui.org/cn/2007/04/generate-all-combinations-of-n-elements-in-r/
https://yihui.org/cn/2007/04/generate-all-combinations-of-n-elements-in-r/
Guest *Yasin Babahanoğlu* @ 2018-04-30 11:29:01 originally posted:
Another way could be:
# Your vector
vec <- c(letters[1:5])
# Create an empty list
lst <- list()
# Define total number combinations from 1-pair to comb_n-pair
comb_n <- length(vec)
# Find all possible combinations up to 5, store it to a list
for (i in 1:comb_n) {
lst[[i]]<- c(combn(vec, i, simplify = FALSE))
}
# For all elements in the list, print pairs
for (i in 1:comb_n) {
# Find length of list number i
k<-length(lst[[i]])
# For all elements in list i, print pairs
for(j in 1:k){
print(lst[[i]][[j]])
}
}Sign in to join the discussion
Sign in with GitHub