【问题标题】:Loop through several post hoc tests in R循环遍历 R 中的几个事后测试
【发布时间】:2017-07-05 08:28:30
【问题描述】:

我有一个名为 data 的数据框。我创建了一个循环遍历变量列表并使用 lapply 为每个变量创建线性模型的函​​数。此方法基于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) 

这很好用。但是,我也想以同样的方式运行事后测试,通常我会通过运行来做到这一点:

TukeyHSD(model)

这在这个例子中显然行不通,但我认为这会:

lapply(model, TukeyHSD)

但这会返回:

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

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

【问题讨论】:

  • 你能用dput(data)提供一些数据吗?
  • 是的,所以我不太愿意在这里上传自己的数据,所以我更改了帖子以包含来自 R 的示例数据集。dput(testDF) 的输出发布在此处:codedump.io/share/TKO5BlEbPgSF/1
  • 伙计,你的代码还有更多问题=varList已定义和varListused,Anova不存在(A..),请测试你自己的代码...
  • 对,好吧,再次修复(并测试)代码。 Anova 需要不同的包,我已将其更改为摘要,它位于 r 基础中

标签: r loops lapply anova tukey


【解决方案1】:

试试:

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

【讨论】:

  • 完美!正是我想要的!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多