Milaa
Milaa

Reputation: 419

Add each element from one list to the corresponding element of the another list in R

I have two lists, with the same length, I want to add the first element of second list to the first element of the first list and so on. here is my example: # the mock Data is

m1<- matrix(c(2,3,4,5), nrow = 2, ncol = 2)
m2<- matrix(c(1,2 ,3,4,5,6), nrow = 2, ncol = 3)
m3<- matrix(c(1,10,6,8 ,3,4,5,6), nrow = 4, ncol = 2)
 m4<-matrix(c(2,5,9,11), nrow = 2,ncol = 2)
 list1 <- list(list(x= c(m1,m4, m3), y=c(m1,m2,m3), z=c(m1,m2,m4)),list(x= c(m4,m2, m3), y=c(m1,m2,m4), z=c(m2,m2,m3)),list(x= c(m1,m2, m3), y=c(m1,m2,m3), z=c(m1,m2,m3)))
list2<- list(list(f=m4),list( g=m4),list( h=m2))

the code for achieving what I want

list1[[1]][[4]]<- list2[[1]][[1]]
list1[[2]][[4]]<- list2[[2]][[1]]
list1[[3]][[4]]<- list2[[3]][[1]]
names(list1[[1]])<- c("x","y","z","f")
names(list1[[2]])<- c("x","y","z","g")
names(list1[[3]])<- c("x","y","z","h")

#My question is how can I do the same with loop or lapply, as my actual data is very long lists not only the length of 3.

Upvotes: 1

Views: 780

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388992

We can use Map and combine the corresponding elements of each list.

Map(c, list1, list2)

#[[1]]
#[[1]]$x
# [1]  2  3  4  5  2  5  9 11  1 10  6  8  3  4  5  6

#[[1]]$y
# [1]  2  3  4  5  1  2  3  4  5  6  1 10  6  8  3  4  5  6

#[[1]]$z
# [1]  2  3  4  5  1  2  3  4  5  6  2  5  9 11

#[[1]]$f
#     [,1] [,2]
#[1,]    2    9
#[2,]    5   11
#....

which is similar to map2 from purrr

purrr::map2(list1, list2, c)

Upvotes: 2

Related Questions