Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine data frames from a nested list

I am having trouble combining data frames that are contained in a nested list with a concise syntax. I have a nested list of the following form:

nestedList <- lapply(1:3,function(y){
  lapply(1:8,function(z){
    data.frame(matrix(rnorm(20), nrow=10))
  })
})

So nestedList contains 3 lists that each contain 8 lists with a data frame. I would like to combine the lists as follows:

tmp1 <- nestedList[[1]][[1]]
tmp2 <- nestedList[[2]][[1]]
tmp3 <- nestedList[[3]][[1]]

expectedResult <- rbind(tmp1,tmp2,tmp3)

I would have expected that the following syntax is valid, but apparently it isn't:

unexpectedResult <- rbind(nestedList[[1:3]][[1]])
like image 345
smonsays Avatar asked Jun 25 '26 08:06

smonsays


2 Answers

Try this.

foo <- lapply(nestedList, function(x) x[[1]])
this <- do.call("rbind", foo)
like image 166
vanao veneri Avatar answered Jun 28 '26 04:06

vanao veneri


I came up with following solution using purrr

my_result <- nestedList %>%
  # extract first dataframe from each nested list
  map(`[[`, 1) %>% 
  # bind rows together
  bind_rows()

And to test that the result is correct

identical(my_result, expectedResult)
[1] TRUE
like image 34
Peter H. Avatar answered Jun 28 '26 03:06

Peter H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!