3

I have a list of lists of dataframes. What I am trying to do can be described by the following:

rbind(datalistpairs[[1]][[1]][[1]],datalistpairs[[1]][[2]][[1]],datalistpairs[[1]][[3]][[1]])

My sublist has j length so in reality I am trying something like (for j times):

rbind(datalistpairs[[1]][[1]][[1]],
datalistpairs[[1]][[2]][[1]],
datalistpairs[[1]][[3]][[1]],...,
datalistpairs[[1]][[j]][[1]])

What is the most efficient way to do it?

The output with three iterations creates an dataframe which looks like this:

      LAT    LON
   31  43.1818 5.2348
   311 43.1818 5.2348
   312 43.1818 5.2348

EDIT: I provide below sample data

datalistpairs = list(list(list(l1 = data.frame(LAT = 1, LON = 2), 
                               l2 = data.frame(LAT = 1, LON = 2)),
                          list(l1 = data.frame(LAT = 1, LON = 2), 
                               l2 = data.frame(LAT = 1, LON = 2))),
                     list(list(l1 = data.frame(LAT = 1, LON = 2), 
                               l2 = data.frame(LAT = 1, LON = 2)),
                         list(l1 = data.frame(LAT = 1, LON = 2), 
                              l2 = data.frame(LAT = 1, LON = 2))))

and my goal is to get:

rbind(datalistpairs[[1]][[1]][[1]],datalistpairs[[1]][[2]][[1]]) 

Hope this helps.

1 Answers1

3

Use map() to extract the first element of each sublist.

library(purrr)

datalistpairs[[1]] %>% map_dfr(~ .[[1]])

#   LAT LON
# 1   1   2
# 2   1   2

The corresponding base R solution:

do.call(rbind, lapply(datalistpairs[[1]], `[[`, 1))

Edit: How to apply to datalistpairs[[i]] where i = 1, 2, 3, ..., n

lapply(1:n, function(i){
  do.call(rbind, lapply(datalistpairs[[i]], `[[`, 1))
})
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51