Binding list of lists with tapply by name

Hi! I'm very new to R and find the array binding kinda hard to understand.

I have a list of lists. Each one of these lists contains 3 data tables. I'm building that list using lapply and want to bind my results together so that I have a list of only 3 items to return. Each one of the 3 lists have a name, so I've been trying to use tapply with names(...), but it doesn't work.

Here is what the list looks like:

Capture

He is my code:

   res = pblapply(
      PlacToTest,
      function (x)EsPaCeSimulation(Mydata, ID_Stand = x, TpsSimul = TpsSimul, UseMixedStdTYPE = UseMixedStdTYPE ))

    tapply(res[[1]], names(res[[1]]), bind_rows)

where res is

    listOfResults = list(
    "EsPaCe" = ResFinal,
    "Natura_inventory" = NaturaInit[[1]],
    "Natura_study" = NaturaInit[[2]]
)

Can someone help me? Thanks!


library(tidyverse)
library(data.table)
library(tidytable)
list_of_list_of_tables <- imap(1:4,
    ~ tidytable::group_split.(iris,Species,.named=TRUE))

str(list_of_list_of_tables,max.level = 2)

#bind all the first nested tables

map_dfr(list_of_list_of_tables,
    ~.[[1]])

#bind all the second nested tables
map_dfr(list_of_list_of_tables,
        ~.[[2]])

# make one large table but mark up where everything came from (orig_list, source -i.e. within that list)
(final_merge <- imap_dfr(
  list_of_list_of_tables,
  ~bind_rows(.x,
    .id = "source"
  ) %>% mutate(orig_list=.y)
))

table(final_merge$source,final_merge$orig_list)

Thanks for your answer, but it doesn't work for my needs. The 3 data tables don't have the same columns and need to be merged separately.
All want to bind all the "EsPaCe" data tables together, all the "Natura_inventory" together and all the "Natura_study" together.

With your example, the final_merge returns all three of the data tables merged together, but with "EsPaCe"'s columns.

The fact that my first answer came up short is a good example of why it can be very useful for a question asker to provide representative example data to better capture their need concretely. You can read a guide here
My simple fix, foregoes the attempt to provide a single data.frame as an answer, and is content just to stitch like tables together maintaining the higher order list.

in your case it would be 1:3 rather than the 1:2 in my example


library(tidyverse)

list_of_list_of_tables <- list( list(hm = head(mtcars),
                                     hi  = head(iris)),
                                list(tm = tail(mtcars),
                                     ti  = tail(iris)))


map(1:2,
    ~{y <- .x
      map_dfr(list_of_list_of_tables,
              ~.[[y]])})

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.