首页 > 解决方案 > R - 遍历 2 个列表并返回一个列表

问题描述

我正在尝试迭代 2 个列表(实际上是 2 个数据集)并按列对它们进行统计比较,然后按列返回结果。

我正在尝试使用 lapply 来执行此操作,但我无法获得正确的语法。这是我的代码的一些示例数据:

### 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)

谢谢你的帮助!

标签: rlistfor-loopiterator

解决方案


如果我理解正确,你想要这个:

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

推荐阅读