了解lm和环境 [英] Understanding lm and environment

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

问题描述

我正在使用参数formuladatana.actionweights执行lm().我的体重存储在一个数字变量中.

  • 当我将公式指定为字符(即formula = "Response~0+.")时,出现一个错误,即权重的长度不正确(即使是).
  • 当我指定不带引号的公式(即formula = Response~0+.)时,该函数可以正常工作.

我在lm()文档中偶然发现了这句话:

所有权重,子集和偏移的计算方式都与公式中的变量相同,即首先在数据中,然后在公式环境中.

这对我来说很难解释,但我感觉它包含了我的问题的答案.

解决方案

(这与您遇到的实际问题无关,[@ DWin已解决此问题,您的Q上有评论者],但仅是为了解释您引用的文档的一部分)

引用的帮助信息意味着,使用相同的过程查找模型公式中的变量/对象引用,与查找提供给参数权重,子集等的变量/对象的过程相同.

R首先在数据对象中,然后在公式的环境(通常是交互使用过程中的全局环境)中,查找公式中引用的对象,并按参数权重,子集和偏移量进行查找. >

文档之所以明确提及这一点,是因为lm()与许多使用模型公式接口的R函数一样,都使用了所谓的标准 non-standard 评估.结果是说一个提供weights = foo,R不必在评估参数时寻找对象foo.相反,它将在提供给data参数的对象中查找名称为foo的对象,如果找不到该对象,则在模型公式附带的环境中(如上所述),该对象不会不一定必须是全球环境.

I'm executing lm() with arguments formula, data, na.action, and weights. My weights are stored in a numeric variable.

  • When I specify formula as a character (i.e. formula = "Response~0+."), I get an error that weights is not of the proper length (even though it is).
  • When I specify formula without the quotes (i.e. formula = Response~0+.), the function works fine.

I stumbled upon this sentence in the lm() documentation:

All of weights, subset and offset are evaluated in the same way as variables in formula, that is first in data and then in the environment of formula.

This is difficult for me to interpret, but I sense that it contains the answer to my question.

解决方案

(This has nothing to do with the real problem you have, [@DWin has addressed that, as have commentators on your Q] but is by way of explanation of the part of the documentation you quote)

The quoted help information means that the same process is used to find the variables/objects references in a model formula as is used to find variables/objects supplied to the arguments weights, subset etc.

R looks for for the objects referenced in the formula and by arguments weights, subset, and offset, first in the data object and then in the environment of the formula (which is usually the global environment during interactive use).

The reason why the docs mention this explicitly is because lm() as with many R functions that employ model-formula interfaces use the so-called standard non-standard evaluation. The up-shot is that say one supplies weights = foo, R won't necessarily look for object foo in evaluating the argument. Instead, it will look for an object with the name foo in the object supplied to the data argument, and if it doesn't find it there, then in the environment attached to the model formula, which as mentioned, doesn't always have to be the global environment.

这篇关于了解lm和环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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