Home > Net >  R - iterating over 2 lists and return a list
R - iterating over 2 lists and return a list

Time:11-12

I am trying to iterate over 2 lists (2 datasets really) and do a statistical comparison of them columnwise, and return the results, columnwise.

I am trying to do this using lapply but I can't get the right syntax. Here is some sample data with my code:

### predat and postdat are the datasets to be compared columnwise
predat<- as.data.frame(matrix(data = rnorm(25), nrow = 25, ncol = 5))
postdat<-as.data.frame(matrix(data = rnorm(25), nrow = 25, ncol = 5))
colnames(predat)<-c("x1","x2","x3","x4","x5")
colnames(postdat)<-c("y1","y2","y3","y4","y5")
predat<-as.list(predat)
postdat<-as.list(postdat)

test_out<-function(x,y){
  
  res<-wilcox.test(x,y, paired = TRUE, alternative = "two.sided")
  return(res)
  
  
}
## I want the results of comparing predat and postdat columnwise in a list
out_all<-lapply(predat,postdat, test_out)

Thanks for any help!

CodePudding user response:

If I understood this correctly, you want this:

output <- purrr::map2(
  .x = predat,
  .y = postdat,
  .f = test_out
)
  • Related