【问题标题】:Convert a list column to single observations in R [duplicate]将列表列转换为R中的单个观察值[重复]
【发布时间】:2021-02-25 19:27:05
【问题描述】:

我有一个数据框,其中每一行都是一个列表。像这样:

> df
 
recipe_id     ingredients      

        1     c("cheese", "milk")
        2     c("egg", "chocolate") 
        3     c("rice", "corn")

我想把它变成:

> df
 
recipe_id     ingredients      

        1     cheese
        1     milk
        2     egg
        2     chocolate
        3     rice
        3     corn

谢谢。

【问题讨论】:

    标签: r list dataframe reshape


    【解决方案1】:

    我们可以在tidyr中使用unnest

    library(tidyr)
    unnest(df, ingredients)
    

    数据

    df <- tibble(recipe_id = 1:3, 
       ingredients = list( c("cheese", "milk"), 
            c("egg", "chocolate") ,  c("rice", "corn")))
    

    【讨论】:

      猜你喜欢
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      相关资源
      最近更新 更多