Reputation: 6759
To generate a new combination of a list of names. I generated a list
with the following R
code:
names1 <- c("A", "B", "C")
lst <- lapply(1:length(names1), function(x) combn(names1, x))
lst
> list
[[1]]
[,1] [,2] [,3]
[1,] "A" "B" "C"
[[2]]
[,1] [,2] [,3]
[1,] "A" "A" "B"
[2,] "B" "C" "C"
[[3]]
[,1]
[1,] "A"
[2,] "B"
[3,] "C"
Now, I would like to turn this list into a vector with the following 7 components, just like this one:
newlst <- c("A", "B", "C", "A, B", "A, C", "B, C", "A, B, C")
In other words, I would like to combine the values within each column into one component of the new vector. unlist(lst)
would not work as it produces 12 individual As, Bs, and Cs without any combinations. Any suggestions would be appreciated.
Upvotes: 0
Views: 40
Reputation: 51582
The function combn
takes a function. So if you pass toString
and unlist
you will get your output, i.e.
unlist(lapply(1:length(names1), function(x) combn(names1, x, toString)))
#[1] "A" "B" "C" "A, B" "A, C" "B, C" "A, B, C"
Upvotes: 4