我有一个名为data的数据框。我创建了一个循环遍历变量列表的函数,并使用lapply为每个变量创建一个线性模型。此方法基于this帖子。
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"
我缺少什么让这项工作?
答案 0 :(得分: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