Reputation: 121
I have a list of vectors and I would like to get a list of all possible combinations between the elements of every vector, i.e., combinations of n elements (from a vector) taken two and more than two at a time.
For instance, I have the following list:
> DF
$`1`
A B C
1 11 2 432
$`2`
A B C
2 11 3 432
$`3`
A B C
3 13 4 241
Here's my code:
> d=list()
> for (j in 1:length(DF)){
+ for (i in 2:length(DF)){
+ d[[j]]=combn(DF[[j]],i,simplify=F)
+ }
+ }
> d
[[1]]
[[1]][[1]]
A B C
1 11 2 432
[[2]]
[[2]][[1]]
A B C
2 11 3 432
[[3]]
[[3]][[1]]
A B C
3 13 4 241
It is wrong, because I just get combinations of three elements taken three at a time. I would have to add combinations of three elements taken two at a time. I just get the last loop value. It is a problem of dimensions inside the loop.
If I run the loop just for i=2, then I get:
> d
[[1]]
[[1]][[1]]
A B
1 11 2
[[1]][[2]]
A C
1 11 432
[[1]][[3]]
B C
1 2 432
[[2]]
[[2]][[1]]
A B
2 11 3
[[2]][[2]]
A C
2 11 432
[[2]][[3]]
B C
2 3 432
....
Upvotes: 3
Views: 125
Reputation: 2239
you could try
lapply(2:3, function(k) { lapply(1:length(DF),function(x){ combn(DF[[x]],k,
simplify = FALSE)})})
Upvotes: 2