Using lapply with data in two lists in R

Viewed 448

I have two lists and I want to use lapply to get a new list

The data is

library(dplyr)
list.A <- list(df1=data.frame(x= c(1:5), y = letters[1:5], z= rep(1,5)),
               df2=data.frame(x= c(10:15), y = letters[5:10], z= rep(10,6)))

list.B <- list(df1=data.frame(x= c(1:6), var2 = letters[10:15], var3= rep(7,6)),
               df2=data.frame(x= c(10,12), var2 = letters[1:2], var3= rep(5,2)))

I want the result to be as following

dat.1 <- left_join(list.A[[1]], list.B[[1]], by=("x"))
dat.2 <- left_join(list.A[[2]], list.B[[2]], by=("x"))

new.list <- list(df1 = dat.1, df2 =dat.2)

But when I use lapply the results are weird and not as I wish them to be

new.list <- lapply(list.A, function(a){lapply(list.B, function(b){
  df <-left_join(a, b, by=("x"))
})
})

Any help, please. I need to apply loop or lapply would work? my actual lists have so many data frames

1 Answers

We need either map2 from purrr as this loops over each corresponding elements of both list and do the left_join by the 'x' column

library(dplyr)
library(purrr)
map2(list.A, list.B, ~ left_join(.x, .y, by = 'x'))

-output

#$df1
#  x y z var2 var3
#1 1 a 1    j    7
#2 2 b 1    k    7
#3 3 c 1    l    7
#4 4 d 1    m    7
#5 5 e 1    n    7

#$df2
#   x y  z var2 var3
#1 10 e 10    a    5
#2 11 f 10 <NA>   NA
#3 12 g 10    b    5
#4 13 h 10 <NA>   NA
#5 14 i 10 <NA>   NA
#6 15 j 10 <NA>   NA

Or Map (from base R)

Map(merge, list.A, list.B, MoreArgs = list(all.x = TRUE, by = 'x'))
Related