How to create a list of an unordered combination of elements in a string vector in R?


An unordered combination of elements means that the combination of the values in a way that does not make any particular arrangement. For example, if we have three values one, two, and three then they can be arranged in the following way which is unordered −

"one"
"two" "three"
"one" "two"
"one" three"
"two" "three"
"one" "two" "three"

Example

 Live Demo

x<-c("India","China","Russia","Canada") unlist(lapply(seq_along(x),combn,x=x,simplify=FALSE),recursive=FALSE)

Output

[[1]]
[1] "India"
[[2]]
[1] "China"
[[3]]
[1] "Russia"
[[4]]
[1] "Canada"
[[5]]
[1] "India" "China"
[[6]]
[1] "India" "Russia"
[[7]]
[1] "India" "Canada"
[[8]]
[1] "China" "Russia"
[[9]]
[1] "China" "Canada"
[[10]]
[1] "Russia" "Canada"
[[11]]
[1] "India" "China" "Russia"
[[12]]
[1] "India" "China" "Canada"
[[13]]
[1] "India" "Russia" "Canada"
[[14]]
[1] "China" "Russia" "Canada"
[[15]]
[1] "India" "China" "Russia" "Canada"

Example

 Live Demo

y<-c("Winter","Rainy","Summer") unlist(lapply(seq_along(y),combn,x=y,simplify=FALSE),recursive=FALSE)

Output

[[1]]
[1] "Winter"
[[2]]
[1] "Rainy"
[[3]]
[1] "Summer"
[[4]]
[1] "Winter" "Rainy"
[[5]]
[1] "Winter" "Summer"
[[6]]
[1] "Rainy" "Summer"
[[7]]
[1] "Winter" "Rainy" "Summer"

Updated on: 14-Oct-2020

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements