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]])
Try this.
foo <- lapply(nestedList, function(x) x[[1]])
this <- do.call("rbind", foo)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With