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

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

问题描述

我有一个名为data的数据框.我创建了一个循环遍历变量列表并使用lapply为每个变量创建线性模型的函​​数.此方法基于帖子.

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

以下是可重现的示例:

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天全站免登陆