在 R 中循环执行几个事后测试 [英] Loop through several post hoc tests in R

查看:40
本文介绍了在 R 中循环执行几个事后测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 data 的数据框.我创建了一个函数,该函数通过变量列表进行循环,并使用 lapply 为每个变量创建一个线性模型.此方法基于 this 帖子.

I have a dataframe called data. I have created a function that loop thorugh a list of variables and creates a linear model for each of them using lapply. This method is based on this post.

library(datasets)
testDF <- data.frame(Salaries)
#creates list of variables

varListTest <- names(testDF)[3:4] 

#creates a model for each of the variables in question
model<- lapply(varListTest, function(x) {
    lm(substitute(i~Rank, list(i = as.name(x))), data = testDF)}) 

#output model
lapply(model, summary) 

这很好用.但是,我也想以相同的方式运行事后测试,通常我会通过运行:

This works great. However, I would also like to run post-hoc tests in the same fashion, normally i would do this by running:

TukeyHSD(model)

这显然在这个例子中不起作用,但我认为这会:

This obviously won't work in this example, but I thought this would:

lapply(model, TukeyHSD)

但这会返回:

no applicable method for 'TukeyHSD' applied to an object of class "lm"

我缺少什么才能完成这项工作?

What am I missing to make this work?

推荐答案

尝试:

lapply(model, function(m) TukeyHSD(aov(m)))

这是一个可重现的例子:

Here is a reproducible example:

testDF=iris


varListTest <- names(testDF)[1:3] 

#creates a model for each of the variables in question
model<- lapply(varListTest, function(x) {
  lm(substitute(i~Species, list(i = as.name(x))), data = testDF)})  


lapply(model, function(model) TukeyHSD(aov(model))) 

提供(截断)

[[1]]
  Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = model)

$Species
                      diff       lwr       upr p adj
versicolor-setosa    0.930 0.6862273 1.1737727     0
virginica-setosa     1.582 1.3382273 1.8257727     0
virginica-versicolor 0.652 0.4082273 0.8957727     0

这篇关于在 R 中循环执行几个事后测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆