Home > database >  Creating a dataframe from a nested list
Creating a dataframe from a nested list

Time:08-04

I have a list that contains 60 lists, one for each participant. Within a list of a participant, there are anywhere between 1 and 20 values of type double.

I would like to create a loop where I add each participant's scores to a dataframe. This dataframe would store participants' scores in long format. So if a participant has 3 list entries, he gets 3 rows in the dataframe. I would also need an ID column.

Participant Score
1 0.02
1 0.04
2 0.08
3 0.01
3 0.03
3 0.04

CodePudding user response:

If it is a nested list of numeric vector, loop over the list with map and bind the inner list element with bind_rows

library(purrr)
library(dplyr)
out <- map_dfr(lst1, ~ bind_rows(.x, .id = 'Participant'), .id = 'ID')

Or if the structure is different, try

library(tibble)
library(tidyr)
map_dfr(lst1, ~ enframe(.x, name = 'Participant', value = 'Score') %>% 
     unnest(cols = Score), .id = 'ID')

CodePudding user response:

I would recommend converting each participant's list to a data frame and then using rbind to combine them into one data frame. For example, if the list is stored in a variable named x :

#convert each participant's list to a data frame
x_dataframes <- lapply(seq_along(x), function(curParticipant){
   return(data.frame(Participant = curParticipant,
                     Score = x[[curParticipant]]))
})

#combine the list of dataframes into one dataframe
x_combined <- do.call("rbind", x_dataframes)
  • Related