本文介绍了为什么不建议在 R 中使用 attach(),我应该使用什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个数据框 x,其中包含 jobincome 列.引用frame中的数据通常需要job列中的数据命令x$jobjob列中的数据x$income命令收入栏.

Let's assume that we have a data frame x which contains the columns job and income. Referring to the data in the frame normally requires the commands x$jobfor the data in the job column and x$income for the data in the income column.

但是,使用命令attach(x) 允许在引用相同数据时取消数据框的名称和$ 符号.因此,在 R 代码中,x$job 变成 job 并且 x$income 变成 income.

However, using the command attach(x) permits to do away with the name of the data frame and the $ symbol when referring to the same data. Consequently, x$job becomes job and x$income becomes income in the R code.

问题是许多 R 专家建议在 R 中编码时不要使用 attach() 命令.

The problem is that many experts in R advise NOT to use the attach() command when coding in R.

造成这种情况的主要原因是什么?应该用什么代替?

What is the main reason for that? What should be used instead?

推荐答案

何时使用:

我使用 attach() 当我希望您在大多数统计数据包(例如 Stata、SPSS)中获得一次处理一个矩形数据集的环境时.

I use attach() when I want the environment you get in most stats packages (eg Stata, SPSS) of working with one rectangular dataset at a time.

何时不使用它:

然而,当你有几个不同的数据集时,它会变得非常混乱并且代码很快变得不可读,特别是如果你实际上使用 R 作为一个原始的关系数据库,其中不同的数据矩形,都与手头的问题相关,也许用于匹配来自不同矩形的数据的各种方式,具有相同名称的变量.

However, it gets very messy and code quickly becomes unreadable when you have several different datasets, particularly if you are in effect using R as a crude relational database, where different rectangles of data, all relevant to the problem at hand and perhaps being used in various ways of matching data from the different rectangles, have variables with the same name.

with() 函数,或许多函数的 data= 参数,是许多 attach() 实例的绝佳替代品很诱人.

The with() function, or the data= argument to many functions, are excellent alternatives to many instances where attach() is tempting.

这篇关于为什么不建议在 R 中使用 attach(),我应该使用什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:17