R: Unlist into a two columns dataframe (name, value)

后端 未结 1 1962
旧巷少年郎
旧巷少年郎 2021-01-25 23:48

From a named list I want to create a two columns data.frame(), with list names appearing in the first column and list elements in the second.

I managed to

相关标签:
1条回答
  • 2021-01-26 00:16

    Converting my comments to an answer, you can use stack from base R, or melt from "reshape2":

    Here's stack:

    head(stack(my_list), 15)
    ##    values        ind
    ## 1       0  one_digit
    ## 2       1  one_digit
    ## 3       2  one_digit
    ## 4       3  one_digit
    ## 5       4  one_digit
    ## 6       5  one_digit
    ## 7       6  one_digit
    ## 8       7  one_digit
    ## 9       8  one_digit
    ## 10      9  one_digit
    ## 11     10 two_digits
    ## 12     11 two_digits
    ## 13     12 two_digits
    ## 14     13 two_digits
    ## 15     14 two_digits
    

    Here's melt:

    head(melt(my_list), 15)
    ##    value         L1
    ## 1      0  one_digit
    ## 2      1  one_digit
    ## 3      2  one_digit
    ## 4      3  one_digit
    ## 5      4  one_digit
    ## 6      5  one_digit
    ## 7      6  one_digit
    ## 8      7  one_digit
    ## 9      8  one_digit
    ## 10     9  one_digit
    ## 11    10 two_digits
    ## 12    11 two_digits
    ## 13    12 two_digits
    ## 14    13 two_digits
    ## 15    14 two_digits
    

    One difference between the two approaches is that melt will automatically create the "L1" column even if the list doesn't have names, and will work with nested lists too.

    head(melt(unname(my_list)), 15)
    ##    value L1
    ## 1      0  1
    ## 2      1  1
    ## 3      2  1
    ## 4      3  1
    ## 5      4  1
    ## 6      5  1
    ## 7      6  1
    ## 8      7  1
    ## 9      8  1
    ## 10     9  1
    ## 11    10  2
    ## 12    11  2
    ## 13    12  2
    ## 14    13  2
    ## 15    14  2
    
    0 讨论(0)
提交回复
热议问题