用 anova 代替 r [英] substitute in r together with anova

查看:34
本文介绍了用 anova 代替 r的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在不同的数据集上运行方差分析,但不太知道该怎么做.我搜索了一下,发现这很有用:https://stats.idre.ucla.edu/r/codefragments/looping_strings/

I tried to run anova on different sets of data and didn't quite know how to do it. I goolged and found this to be useful: https://stats.idre.ucla.edu/r/codefragments/looping_strings/

hsb2 <- read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv")
names(hsb2)
varlist <- names(hsb2)[8:11]
models <- lapply(varlist, function(x) {
lm(substitute(read ~ i, list(i = as.name(x))), data = hsb2)
})

我对上述代码的理解是它创建了一个函数 lm() 并将其应用于 varlist 中的每个变量,并对每个变量进行线性回归.

My understanding of what the above codes does is it creates a function lm() and apply it to each variable in varlist and it does linear regression on each of them.

所以我认为使用 aov 而不是 lm 会像这样对我有用:

So I thought use aov instead of lm would work for me like this:

aov(substitute(read ~ i, list(i = as.name(x))), data = hsb2)

但是,我收到此错误:

Error in terms.default(formula, "Error", data = data) : 
no terms component nor attribute

我不知道错误来自哪里.请帮忙!

I have no idea of where the error comes from. Please help!

推荐答案

问题在于 substitute() 返回一个表达式,而不是一个公式.我认为@thelatemail 对

The problem is that substitute() returns an expression, not a formula. I think @thelatemail's suggestion of

lm(as.formula(paste("read ~",x)), data = hsb2)

是一个很好的解决方法.或者,您可以评估表达式以获得公式

is a good work around. Alternatively you could evaluate the expression to get the formula with

models <- lapply(varlist, function(x) {
    aov(eval(substitute(read ~ i, list(i = as.name(x)))), data = hsb2)
})

我想这取决于您之后想对模型列表做什么.做

I guess it depends on what you want to do with the list of models afterward. Doing

models <- lapply(varlist, function(x) {
    eval(bquote(aov(read ~ .(as.name(x)), data = hsb2)))
})

为每个结果提供一个更干净的"call 属性.

gives a "cleaner" call property for each of the result.

这篇关于用 anova 代替 r的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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