最近在看《R语言实战》看到第九章,运行代码清单9-3的时候,运行结果和书上不同,并且报错
图1 书上的原文
图2 运行结果1
图3 运行结果2
> aggregate(weight, by=list(dose), FUN=mean)
Error in aggregate.data.frame(as.data.frame(x), ...) : 参数的长度必需一样
> fit <- aov(weight ~ gesttime + dose)
Error in model.frame.default(formula = weight ~ gesttime + dose, drop.unused.levels = TRUE) :
变数的长度不一样('dose')
>
> library(effects)
lattice theme set by effectsTheme()
See ?effectsTheme for details.
> effect("dose", fit)
NOTE: dose does not appear in the model
Error in Analyze.model(focal.predictors, mod, xlevels, default.levels, :
the following predictor is not in the model: dose
------
NOTE: dose does not appear in the model
Error in model.frame.default(weight ~ litter$gesttime + litter$dose + :
参数'litter'的种类(list)不对
In addition: Warning message:
Using `$` in model formulas can produce unexpected results. Specify
your model using the `data` argument instead.
Try: weight ~
gesttime + dose, data = litter
错误提示信息
在网上搜了一下报错的信息,找到了这篇文章
- Reference variables directly (e.g.
lm(ds$x ~ ds$y)
)
直接使用“$”符号(如果变量名较短,重复次数较少时)- Specify the dataframe for commands which support this (e.g.
lm(y ~ x, data=ds)
)
直接说明命令的数据来源,例如:lm(y ~ x, data=ds)
- Use the
with()
function, which returns the value of whatever expression is evaluated (e.g.with(ds,lm(y ~x))
)
使用with()
函数,它会返回被评估的任何表达式的值,例如with(ds,lm(y~x))
作者:明明就_faf8
链接:https://www.jianshu.com/p/9fed07a72472
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
于是,我把书上要运行的代码改为
data(litter, package = "multcomp")
attach(litter)
table(litter$dose)
aggregate(weight, by = list(litter$dose), FUN = mean)
fit <- aov(weight ~ gesttime + dose, data = litter)
summary(fit)
这样运行的结果就和书上一致了。
分析原因:在其他数据集中出现过dose变量,并且我的工作目录没有该过,所以可能出现了dose指代不明的情况。在dose变量前指明数据集即可。
目前还能遇到这些提示
The following object is masked _by_ .GlobalEnv:
dose
The following objects are masked from litter (pos = 3):
dose, gesttime, number, weight
The following objects are masked from litter (pos = 4):
dose, gesttime, number, weight
The following objects are masked from litter (pos = 5):
dose, gesttime, number, weight
The following object is masked from ToothGrowth (pos = 6):
dose
The following object is masked from ToothGrowth (pos = 7):
dose
另外attach()函数还是不太熟悉。如有更好的办法或者指导,评论区见。