我在使用R语言的时候,经常会遇到“ the following objects are masked from data (pos=3)”这样的提示,因为每次都能运行出结果,所以每次也都没管它。直到我今天跑循环的时候,这个东西真的让我好烦,就想搞清楚怎么回事,再消除这样的提示。百度了许久,网上并没有合适的答案,于是去了外网搜索,结果如下:
标题很是有意思哈:
还是看正文吧:
R objects that reside in other R objects can require a lot of typing to access. For example, to refer to a variable x
in a dataframe df
, one could type df$x
. This is no problem when the dataframe and variable names are short, but can become burdensome when longer names or repeated references are required, or objects in complicated structures must be accessed.
大概翻译:实践中,我们想使用数据框
df
中的x
通常会用命令df$x
即可,但是当名字较长或者要重复很多次的时候就很繁琐了。
The attach()
function in R can be used to make objects within dataframes accessible in R with fewer keystrokes. As an example:
在这种情况下,
attach()
命令则会让我们轻松许多,即减少工作量。例如:
ds <- read.csv("http://www.math.smith.edu/r/data/help.csv")#读取数据
names(ds)
attach(ds) #加载ds数据
mean(cesd)
[1] 32.84768 #结果
... then detach()
the dataset to clean up after ourselves.
之后,用命令detach()
结束使用数据集。
users are cautioned that if there is already a variable called cesd
in the local workspace, issuing attach(ds)
, may not mean that cesd
references ds$cesd
. Name conflicts of this type are a common problem with attach()
and care should be taken to avoid them.
- 用户应注意,如果本地工作空间中已存在名为
cesd
的变量,则使用attach(ds)
可能并不意味着cesd
是ds$cesd
之意。这种类型的名称冲突是attach()的常见问题
,应注意避免它们。
The help page for attach()
notes that attach can lead to confusion. The Google R Style Manual provides clear advice on this point, providing the following advice about attach()
: The possibilities for creating errors when using attach are numerous. Avoid it.
attach()
的help页面提示说“使用attach命令可能会导致混淆”。关于这一点,Google R Style Manual给出了明确的建议:使用attach()
导致的错误可能有很多,避免使用它!
So what options exist for those who decide to go cold turkey?
那么,有哪些应对方法呢?
- 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))
(Also note the within()
function, which is similar to with()
, but returns a modified object.)
注:
within()
函数和with()
函数是近似的。
Some examples may be helpful:
比如下面这个例子:
直接用$符号:
> lm1 <- lm(cesd ~ pcs, data=ds)
> mean(ds$cesd[ds$female==1]) # these next three are equivalent
[1] 36.88785
或者用with命令:
> with(ds, mean(cesd[female==1]))
[1] 36.88785
> with(subset(ds, female==1), mean(cesd))
[1] 36.88785
In short, there’s never an actual need to use attach()
, using it can lead to confusion or errors, and alternatives exists that avoid the problems. We recommend against it.
- 简而言之,我们没有必要使用attach(),因为它会导致混淆或错误,何况我们有其它替代方案。
- 故,我们建议不使用它!
结论:尽量不用 attach 命令!
- 替代它的 with 命令怎么用?
with(data,{...})
详细语法可以在R中输入??with
查看。
文献参考:https://www.r-bloggers.com/to-attach-or-not-attach-that-is-the-question/