I have a function (too lengthy to paste here) which will output a list containing two elements which are both data.tables - let's call them AA and BB. Each individual data.table will always have the same number of columns for the function calls, but the row numbers may differ. AA and BB do not have matching column names.
This function will be called multiple times and I want to combine ('rbind') all of the AA and BB data.tables (separately) from the function calls into two larger data.tables within a list.
To show what I mean, I've created two lists (A and B) which each contain two data.tables (AA and BB).
require(data.table)
A_1 <- data.table(A = 1:2,B = 2:3)
A_2 <- data.table(C = 100:102,D = 300:302)
A <- list(AA = A_1,BB = A_2)
B_1 <- data.table(A = 2:4,B = 1:3)
B_2 <- data.table(C = 10:12,D = 20:22)
B <- list(AA = B_1,BB = B_2)
Return_list <- function(Name){
return(get(Name))
}
Now create the object "List" which is a combination of lists A and B
List <- lapply(c("A","B"),Return_list)
My intended output would be given by the following (in the case where I only called the function twice):
List_output <- list(AA = rbind(A_1,B_1),BB = rbind(A_2,B_2))
I have looked at a lot of examples on SO where data.tables within a list were combined into one; however in this case I want to combine them into two and I can't seem to apply the logic from other examples.
I've played around with rbindlist, unlist(...,recursive = FALSE) and a whole host of other things but have not come close unfortunately.
Any help would be greatly appreciated. Thanks in advance.
We can use
library(tidyverse)
list(A, B) %>%
transpose %>%
map(bind_rows)
Or with rbindlist from data.table
library(data.table)
Map(function(...) rbindlist(list(...)), A, B)
You can use the map2 function from the purrr package to get where you want to be:
library(purrr)
List_output <- map2(A, B, rbind)
List_output
$`AA`
A B
1: 1 2
2: 2 3
3: 2 1
4: 3 2
5: 4 3
$BB
C D
1: 100 300
2: 101 301
3: 102 302
4: 10 20
5: 11 21
6: 12 22
Or the Map function from base R:
Map(rbind, A, B)
$`AA`
A B
1: 1 2
2: 2 3
3: 2 1
4: 3 2
5: 4 3
$BB
C D
1: 100 300
2: 101 301
3: 102 302
4: 10 20
5: 11 21
6: 12 22
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