Djiggy - 1 year ago 79

R Question

I would like to generate a list of all combinations of different elements. I found the expand.grid function which seems to be doing a great job.

`lCombi<-expand.grid(c(1,2),c(4,5,6),c(7,8))`

Var1 Var2 Var3

1 1 4 7

2 2 4 7

3 1 5 7

4 2 5 7

5 1 6 7

6 2 6 7

7 1 4 8

8 2 4 8

9 1 5 8

10 2 5 8

11 1 6 8

12 2 6 8

Now, if I understand well, this is a list of 3 elements of 12 rows. But what I would like is a list of 12 elements of 3. I tried to transpose it, convert it into a matrix then back to a list but none worked. So I used my pre-R way of doing things and came up with :

`iLength=nrow(lCombi)`

lResult<-list()

for(i in 1:iLength){

lResult[[i]]<-lCombi[i,]

}

to get my lResult list, which contains what I want. Could you please tell me the more efficient way of doing this please ?

Answer Source

The `split`

function is great at chopping up a data.frame in to a list of data.frames:

```
lResult <- split(lCombi, 1:nrow(lCombi))
```

If you'd like each list element to be a vector instead, use

```
lapply(lResult, unlist)
```