How to 'unlist' a column in a data.table

后端 未结 2 581
名媛妹妹
名媛妹妹 2021-01-04 07:19

in my table, some cells are vectors instead of single value, i.e. the column is a list instead of vector:

dt1 <- data.table(
  colA=   c(\'A1\',\'A2\',\'A         


        
相关标签:
2条回答
  • 2021-01-04 07:33

    I think @Jaap's is easiest, but here's another alternative to chew over:

    #create ID column
    dt1[ , ID := .I]
    
    #unnest colB, keep ID column
    dt_unnest = dt1[ , .(ID = rep(ID, lengths(colB)),
                         colB = unlist(colB))]
    #merge
    dt_unnest = dt_unnest[dt1[ , !'colB'], on = 'ID']
    #    ID colB colA colC colD
    # 1:  1   B1   A1   C1   D1
    # 2:  2  B2a   A2   C2   D2
    # 3:  2  B2b   A2   C2   D2
    # 4:  3   B3   A3   C3   D3
    
    0 讨论(0)
  • 2021-01-04 07:40

    Promoting my comment to an answer. Using:

    dt1[,.(colB = unlist(colB)), by = setdiff(names(dt1), 'colB')]
    

    gives:

       colA colC colD colB
    1:   A1   C1   D1   B1
    2:   A2   C2   D2  B2a
    3:   A2   C2   D2  B2b
    4:   A3   C3   D3   B3
    

    Or as an alternative (a slight variation of @Frank's proposal):

    dt1[rep(dt1[,.I], lengths(colB))][, colB := unlist(dt1$colB)][]
    
    0 讨论(0)
提交回复
热议问题