Reshape matrix into a list of lists

后端 未结 3 1043
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 03:35

I have a list as follows:

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

There are multiple ID

相关标签:
3条回答
  • 2021-01-25 03:45

    I'd just split() the 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
    
    0 讨论(0)
  • 2021-01-25 03:55

    You could also use tapply if you want to stick with base 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"))
    
    0 讨论(0)
  • 2021-01-25 03:55

    The functions in package plyr should be of help here.

    In the following example I assume your data is in the form of a data.frame - even if it really is a list, as you say, it should be straight-forward to convert to a 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 a list as 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
    
    0 讨论(0)
提交回复
热议问题