与方差分析一起替代r [英] substitute in r together with anova

查看:122
本文介绍了与方差分析一起替代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)

但是,我遇到了这个错误:

However, I got this error:

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.

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

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