kmace
kmace

Reputation: 2044

Create a nested data.frame from separate lists

I'd like to create a nested data.frame similar to nesting in the tidyr package. but I do not yet have my data in a data.frame so I cannot simply df %>% group_by(thing) %>% nest() I have 3 lists that correspond to the three columns I'm trying to bring together. See the example below:

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))

Now this is what I would like to do:

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

But of course this wont work as details is not a list of atomics, but rather a list of data.frames. I've also tried:

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

Upvotes: 2

Views: 644

Answers (1)

kmace
kmace

Reputation: 2044

For those of you who run into a similar problem. the key is to use a tibble instead of a 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)

Upvotes: 3

Related Questions