Note the input shape I am dealing with is not the same as in these similar questions: R list of lists to data.frame Converting a list of lists to a dataframe in R: The Tidyverse-way
I am working with a web api which returns results in this shape
listOfListsOfKeyVals <- lapply(1:5, function(i){
list(
col1 = i,
col2 = runif(1)
)
})
You might think that the following will work
do.call(rbind, listOfListsOfKeyVals)
But on closer inspection the result is actually a dataframe of lists
do.call(rbind, listOfListsOfKeyVals) |> tibble()
# A tibble: 5 × 1
`do.call(rbind, listOfListsOfKeyVals)`[,"col1"] [,"col2"]
<list> <list>
1 <int [1]> <dbl [1]>
2 <int [1]> <dbl [1]>
3 <int [1]> <dbl [1]>
4 <int [1]> <dbl [1]>
5 <int [1]> <dbl [1]>
I have come up with the following solution
foreach(x = listOfListsOfKeyVals, .combine = rbind) %do% {
as.data.frame(x)
} |> tibble()
But it is painfully slow for large data sets. Is there a better way?