Add new column to the list of lists and fill it with the values of another list of lists

I have two list of lists with same length
A1<- list(list(data.frame(x=c(1:10),y=c(1:10)),data.frame(x=rep(1,10),y=rep(2,10))),list(data.frame(x=c(11:20),y=c(11:20)),data.frame(x=rep(11,10),y=rep(12,10))))

A2<- list(list(data.frame(x=rep(30,10)),data.frame(x=rep(40,10))),list(data.frame(x=rep(50,10)),data.frame(x=rep(60,10))))

I want to add a new column to the data frames existed in A1and fill it values from A2

in the end, the A1 " list of lists" should look like the following
A3<- list(list(data.frame(x=c(1:10),y=c(1:10),z=rep(30,10)),data.frame(x=rep(1,10),y=rep(2,10),z=rep(40,10))),list(data.frame(x=c(11:20),y=c(11:20),z=rep(50,10)),data.frame(x=rep(11,10),y=rep(12,10),z=rep(60,10))))

I have tried the following code, but it didn't work
A3<- mapply(function(X,Y) {
X$z<- Y
}, X=A1, Y=A2)

This is ugly, but it gets to the goal.

A1<- list(list(data.frame(x=c(1:10),y=c(1:10)),data.frame(x=rep(1,10),y=rep(2,10))),
          list(data.frame(x=c(11:20),y=c(11:20)),data.frame(x=rep(11,10),y=rep(12,10))))

A2<- list(list(data.frame(x=rep(30,10)),data.frame(x=rep(40,10))),
          list(data.frame(x=rep(50,10)),data.frame(x=rep(60,10))))

A3<- list(list(data.frame(x=c(1:10),y=c(1:10),z=rep(30,10)),
               data.frame(x=rep(1,10),y=rep(2,10),z=rep(40,10))),
          list(data.frame(x=c(11:20),y=c(11:20),z=rep(50,10)),
               data.frame(x=rep(11,10),y=rep(12,10),z=rep(60,10))))
library(purrr)
#> Warning: package 'purrr' was built under R version 3.5.3
tmp1 <- unlist(A1, recursive = FALSE)
tmp2 <- unlist(A2, recursive = FALSE)
A4 <- map2(.x = tmp1, .y = tmp2, .f = ~ cbind(.x, .y))
A4 <- lapply(A4, function(x) {colnames(x) <- c("x","y","z"); x})
A5 <- vector("list", length = length(A4)/2)
for (i in 1:(length(A4)/2) ) {
  A5[[i]] <- list(A4[[i * 2 - 1]], A4[[i * 2]])
}
identical(A3, A5)
#> [1] TRUE

Created on 2019-11-16 by the reprex package (v0.3.0.9000)

1 Like

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