Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

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

$
0
0

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.


Viewing all articles
Browse latest Browse all 201945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>