Home > OS >  convert nested list to data frame
convert nested list to data frame

Time:09-07

I am trying to convert a nested list into a data frame. I want to get a data frame from the 3 dimension. Until now I specify with the counter i which dimension of the nested list I getas data frame but I want to get the data frame together from dimension 1, 2 and 3.

Thanks for your help

l <- list(list(list(x = 1, y = 2, 3, 4),
          list(x = 3, y = 4, 5, 6)),
          list(list(x = 1, y = 2, 3, 4)),
          list(list(x = 2, y = 3, 4, 5)))


i = 3

a <-  data.frame(do.call(rbind, l[[i]]))

CodePudding user response:

Like this?

library(tibble)
library(tidyr)

enframe(l) %>% 
  unnest(value) %>% 
  unnest_wider(value)
   name     x     y  ...3  ...4
  <int> <dbl> <dbl> <dbl> <dbl>
1     1     1     2     3     4
2     1     3     4     5     6
3     2     1     2     3     4
4     3     2     3     4     5

CodePudding user response:

This is a bit awkward because of the inconsisteny nesting levels, but we could write a recursive function to extract the lists that have "x" in their name. For example

find_x <- function(x) {
  if (is.list(x) && !"x" %in% names(x)) {
    return(do.call("rbind", lapply(x, find_x)))
  } else if ( !is.list(x)) {
    return(NULL)
  } else {
    return(x)
  }
}
find_x(l)
#      x y    
# [1,] 1 2 3 4
# [2,] 3 4 5 6
# [3,] 1 2 3 4
# [4,] 2 3 4 5

You can change the "x" part to whatever marker you have for your own data of interest

  •  Tags:  
  • r
  • Related