Change matrix to list of lists

I have a list:

id | value ---------- 4 600 4 899 7 19 13 4930 13 300 : : 

There are several repetitions of identifiers, each of which has a unique meaning. I want to turn this into the following:

 id | list ---------- 4 c(600, 899) 7 c(19) 13 c(4930, 300) : : 

Is there a vectorized method for doing this?


EDIT: Extending the first question, is there an easy way to do the same for the common MxN matrix? Ie turning it:

  id | value1 value2 ------------------- 4 600 a 4 899 b 7 19 d 13 4930 e 13 300 a : : : 

in it:

 id | list ---------- 4 list(c(600, 899),c('a','b')) 7 list(c(19),c('b')) 13 list(c(4930, 300),c('e','a')) : : 

Thanks!

+1
source share
3 answers

You can also use tapply if you want to stick with the basic functions:

 tapply(dat$value,dat$id,c) $`4` [1] 600 899 $`7` [1] 19 $`13` [1] 4930 300 

Edit:

For your edited problem, I would go with split and lapply :

 x <- lapply(split(dat[2:3],dat$id),c,use.names=F) dput(x) structure(list(`4` = list(c(600, 899), c("a", "b")), `7` = list( 19, "d"), `13` = list(c(4930, 300), c("e", "a"))), .Names = c("4", "7", "13")) 
+4
source

The functions in the plyr package should help here.

In the following example, I assume that your data is in the form of data.frame - even if it is really a list, as you say, it should be direct to convert to data.frame:

 dat <- data.frame( id = c(4, 4, 7, 13, 13), value = c(600, 899, 19, 4930, 300) ) library(plyr) dlply(dat, .(id), function(x)x$value) 

The result is the list you specified:

 $`4` [1] 600 899 $`7` [1] 19 $`13` [1] 4930 300 attr(,"split_type") [1] "data.frame" attr(,"split_labels") id 1 4 2 7 3 13 
+4
source

I would just split() data:

 d <- read.table(text = "id value 4 600 4 899 7 19 13 4930 13 300", header=T) split(d$value, d$id) $`4` [1] 600 899 $`7` [1] 19 $`13` [1] 4930 300 
+3
source

All Articles