以类似于实际问题的示例为例,为什么不这样做:
library("multcomp")
data("mtcars")
mtcars$gear <- factor(mtcars$gear)
mtcars$cyl <- factor(mtcars$cyl)
xv <- c("gear","cyl")
ll <- list("Dunnett")
for(v in xv){
fo <- as.formula(paste("mpg",v,sep="~"))
fit <- lm(fo,data=mtcars)
names(ll) <- v
print(summary(glht(fit, linfct = do.call(mcp, ll))))
}
这使:
Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Dunnett Contrasts
Fit: lm(formula = fo, data = mtcars)
Linear Hypotheses:
Estimate Std. Error t value Pr(>|t|)
4 - 3 == 0 8.427 1.823 4.621 0.000144 ***
5 - 3 == 0 5.273 2.431 2.169 0.072493 .
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)
Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Dunnett Contrasts
Fit: lm(formula = fo, data = mtcars)
Linear Hypotheses:
Estimate Std. Error t value Pr(>|t|)
6 - 4 == 0 -6.921 1.558 -4.441 0.000235 ***
8 - 4 == 0 -11.564 1.299 -8.905 1.71e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)
这里的技巧是要注意第一个参数mcp
是...
通常意味着我们可以传入表单的列表list(tag = value)
。我们不能tag
在v
这里指定,所以只需ll
使用单个元素创建列表,"Dunnett"
然后在循环中将此列表的名称v
属性更改为. 然后用这个参数列表do.call()
来安排调用。mcp()
为了完整起见,正如@Josh 在上面的评论中提到的那样,从@Hadley 的这个答案中,可以使用该setNames()
函数更简洁地说明该列表:
for(v in xv){
fo <- as.formula(paste("mpg",v,sep="~"))
fit <- lm(fo,data=mtcars)
print(summary(glht(fit, linfct = do.call(mcp, setNames(list("Dunnett"), v)))))
}