【问题标题】:Extract nested data from a dataframe从数据框中提取嵌套数据
【发布时间】:2020-07-30 20:11:54
【问题描述】:

我有以下可重现的示例。有点棘手,这是关于嵌套数据的复杂结构。

name <- c("impressions_unique","impressions_paid_unique","impressions_organic_unique")
period <- c("lifetime","lifetime","lifetime")
l1 <- list(data.frame(value = 33395))
l2 <- list(data.frame(value = 0))
l3 <- list(data.frame(value = 33395))
values <- c(l1,l2,l3)
title <- c("Lifetime Post Total Reach","Lifetime Post Paid Reach","Lifetime Post organic reach")
description <- c("Lifetime","Lifetime","Lifetime")
id <- c(125698,432566,759832)

df <- data.frame(name,period,title,description,id)
df$values <- values


name <- c("impressions_unique","impressions_paid_unique","impressions_organic_unique")
period <- c("lifetime","lifetime","lifetime")
l3 <- list(data.frame(value = 12345))
l4 <- list(data.frame(value = 55))
l5 <- list(data.frame(value = 12400))
values2 <- c(l3,l4,l5)
title <- c("Lifetime Post Total Reach","Lifetime Post Paid Reach","Lifetime Post organic reach")
description <- c("Lifetime","Lifetime","Lifetime")
id2 <- c(023698,212566,356832)

df1 <- data.frame(name,period,title,description,id)
df1$values <- values2


 Message <- c("The weather is sunny","Tomorrow is going to be raining")
 insights.data <- c(list(df),list(df1))
 created_time <- c(2020-02-28, 2020-02-25)
 ID <- c(062742003618463-1401305690071373,062742003618463-1401305690071374)

 full_df <- data.frame(Message,created_time,ID)
 full_df$insights.data <- insights.data

我想拥有 full_df 的列(insights.data 除外)以及三列:“impressions_unique”、“impressions_paid_unique”、“impressions_organic_unique”以及它们各自的值。 所以最终的数据框应该由以下列组成:

   Message,impressions_unique,impressions_paid_unique,impressions_organic_unique,created_time,ID

任何帮助将不胜感激。

【问题讨论】:

    标签: r list dataframe nested


    【解决方案1】:

    可以使用 tidyr 包中的 unnest() 解压嵌套结构。您需要执行两次,因为insights.data 是一个包含数据框的列表,而在该数据框内的值是另一个包含数据框的列表。 这将使行数增加 3 倍,因为instances.data 列中的数据框有三行。我们可以使用pivot_wider()(也来自 tidyr 包。在以前的版本中名称为spread())将这些行转换为列。

    我希望我已经正确理解了这个问题。

    library(dplyr)
    library(tidyr)
    
    full_df %>% 
      unnest(insights.data) %>% 
      unnest(values) %>% 
      select(Message, created_time, ID, name, value) %>% 
      pivot_wider(names_from = name, values_from = value)
    

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 2016-05-08
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      相关资源
      最近更新 更多