“unpacking” a factor list from a data.frame

后端 未结 6 987
南旧
南旧 2020-12-06 13:34

I\'m new to R / having the option to easily re-organize data, and have hunted around for a solution but can\'t find exactly what I\'d like to do. Reshape2\'s melt/cast doesn

6条回答
  •  [愿得一人]
    2020-12-06 13:35

    A plodding but seemingly robust solution:

    ## Some example data
    df <- as.data.frame(cbind(ID = paste0("ID", 1:2), 
                              category_list = list(4:1, 2:3), 
                              xvar = 8:9, 
                              yvar = 10:9))
    
    ## Calculate number of times each row of df will be repeated 
    nn <- sapply(df$category_list, length)  
    ii <- rep(seq_along(nn), times=nn)       
    
    ## Reshape data.frame
    transform(df[ii,], 
              category = unlist(df$category_list),
              category_list = NULL, 
              row.names = NULL)
    #    ID xvar yvar category
    # 1 ID1    8   10        4
    # 2 ID1    8   10        3
    # 3 ID1    8   10        2
    # 4 ID1    8   10        1
    # 5 ID2    9    9        2
    # 6 ID2    9    9        3
    

提交回复
热议问题