[英]R: iterate a function over two lists simultaneously using lapply?
我有多个因素在划分我的数据。
通过一个因素( uniqueGroup
),我想对数据进行子集;通过另一个因素( distance
),我想首先通过“移动阈值”对数据进行分类,然后测试组之间的统计差异。
我创建了一个movThreshold
函数对数据进行分类,并通过wilcox.test
对其进行wilcox.test
。 为了改变不同的阈值,我只是运行
lapply(th.list, # list of thresholds
movThreshold, # my function
tab = tab, # original data
dependent = "infGrad") # dependent variable
现在我意识到,实际上我首先需要通过uniqueGroup
来对数据进行子集设置 , 然后再更改阈值 。 但是我不确定如何在我的lapply
代码中编写它?
我的虚拟数据:
set.seed(10)
infGrad <- c(rnorm(20, mean=14, sd=8),
rnorm(20, mean=13, sd=5),
rnorm(20, mean=8, sd=2),
rnorm(20, mean=7, sd=1))
distance <- rep(c(1:4), each = 20)
uniqueGroup <- rep(c("x", "y"), 40)
tab<-data.frame(infGrad, distance, uniqueGroup)
# Create moving threshold function &
# test for original data
# ============================================
movThreshold <- function(th, tab, dependent, ...) {
# Classify data
tab$group<- ifelse(tab$distance < th, "a", "b")
# Calculate wincoxon test - as I have only two groups
test<-wilcox.test(tab[[dependent]] ~ as.factor(group), # specify column name
data = tab)
# Put results in a vector
c(th, unique(tab$uniqueGroup), dependent, uniqueGroup, round(test$p.value, 3))
}
# Define two vectors to run through
# unique group
gr.list<-unique(tab$uniqueGroup)
# unique threshold
th.list<-c(2,3,4)
如何在两个列表上运行lapply
?
lapply(c(th.list,gr.list), # iterate over two vectors, DOES not work!!
movThreshold,
tab = tab,
dependent = "infGrad")
在我的上一个问题( Kruskal-Wallis测试:创建对子集data.frame的lapply函数? )中,我学习了如何遍历表中的各个子集:
lapply(split(tab, df$uniqueGroup), movThreshold})
但是如何遍历子集和阈值呢?
如果我正确理解了您要执行的操作,请使用以下data.table
解决方案:
library(data.table)
setDT(tab)[, lapply(th.list, movThreshold, tab = tab, dependent = "infGrad"), by = uniqueGroup]
另外,您可以只执行嵌套的lapply
。
lapply(gr.list, function(z) lapply(th.list, movThreshold, tab = tab[uniqueGroup == z, ], dependent = "infGrad"))
抱歉,如果我误解了您要做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.