从单独的列表

时间:2017-12-03 06:52:46

标签: r tidyr tidyverse

我想创建一个嵌套的data.frame,类似于tidyr包中的嵌套。但我还没有data.frame中的数据,所以我不能简单df %>% group_by(thing) %>% nest()我有3个列表,对应于我想要汇集的三个列。请参阅以下示例:

library(tidyverse)

student = c('bob', 'jane', 'sam')
avg_score = c(95, 99, 80)
details = lapply(1:3, 
           function(x) data.frame(answer = sample(c(TRUE, FALSE),10, TRUE), 
                                  question_num = 1:10))

现在这就是我想做的事情:

my_data_frame = data.frame(student = student, 
                           avg_score = avg_score, 
                           details = details)

但当然这不会起作用,因为details不是原子列表,而是data.frame的列表。我也试过了:

my_data_frame = data.frame(student = student, 
                           avg_score = avg_score, 
                           details = nest(details))

1 个答案:

答案 0 :(得分:2)

对于那些遇到类似问题的人。关键是使用tibble而不是data.frame

library(tidyverse)

student = c('bob', 'jane', 'sam')
avg_score = c(95, 99, 80)
details = lapply(1:3, function(x) data.frame(answer = sample(c(TRUE, FALSE), 10, TRUE), question_num = 1:10))

my_nested_data_frame = tibble(student = student, avg_score = avg_score, details = details)