将列表列转换为 R 中的单个观察值 数据

问题描述

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

> 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

谢谢。

解决方法

我们可以在unnest中使用tidyr

library(tidyr)
unnest(df,ingredients)

数据

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