什么时候使用 'with' 函数,为什么它好?

When to use 'with' function and why is it good?

使用with()有什么好处?在帮助文件中,它提到它在从数据创建的环境中评估表达式。这样做有什么好处?与仅在全球环境中评估相比,创建环境并在其中进行评估是否更快?或者还有什么我想念的吗?

当我不想继续打字时我会使用它dataframe$。例如

with(mtcars, plot(wt, qsec))

而不是

plot(mtcars$wt, mtcars$qsec)

前者在mtcarsdata.frame中查找wtqsec。当然

plot(qsec~wt, mtcars)

更适合使用 data= 参数的绘图或其他函数。

with 是对没有 data 参数的函数的包装

有许多函数可以处理数据框并采用 data 参数,因此您无需在每次引用列时都重新键入数据框的名称。 lmplot.formulasubsettransform 只是几个例子。

with 是一个通用的 wrapper,让您可以像使用数据参数一样使用任何函数。

使用 mtcars 数据集,我们可以使用或不使用数据参数来拟合模型:

# this is obviously annoying
mod = lm(mtcars$mpg ~ mtcars$cyl + mtcars$disp + mtcars$wt)

# this is nicer
mod = lm(mpg ~ cyl + disp + wt, data = mtcars)

但是,如果(出于某种奇怪的原因)我们想找到 cyl + disp + wtmean,就会出现问题,因为 mean 没有像 lm 确实如此。这是 with 解决的问题:

# without with(), we would be stuck here:
z = mean(mtcars$cyl + mtcars$disp + mtcars$wt)

# using with(), we can clean this up:
z = with(mtcars, mean(cyl + disp + wt))

with(data, foo(...)) 中包装 foo() 让我们可以使用任何函数 foo 就好像 它有一个 data 参数一样 - 这也就是说我们可以使用不带引号的列名,防止重复 data_name$column_namedata_name[, "column_name"].

何时使用with

只要您喜欢交互式(R 控制台)和在 R 脚本中使用 with 即可节省输入并使您的代码更清晰。您需要为单个命令 re-type 您的数据框名称的频率越高(并且您的数据框名称越长!),使用 with.

的好处就越大

另请注意,with 不限于数据帧。来自 ?with:

For the default with method this may be an environment, a list, a data frame, or an integer as in sys.call.

我不经常使用环境,但当我使用时,我发现 with 非常方便。

当您只需要一行的结果时

正如@Rich Scriven 在评论中建议的那样,当您需要使用 rle 之类的结果时,with 会非常有用。如果您只需要一次结果,那么他的示例 with(rle(data), lengths[values > 1]) 让您可以匿名使用 rle(data) 结果。

何时避免with

一个data参数时

许多具有 data 参数的函数在调用它时使用它不仅仅是为了更简单的语法。大多数建模函数(如 lm)和许多其他函数(ggplot!)使用提供的 data 做很多事情。如果您使用 with 而不是 data 参数,您将限制可用的功能。 如果有 data 参数,请使用 data 参数,而不是 with

添加到环境中

在我上面的示例中,结果被分配给全局环境 (bar = with(...))。要在 list/environment/data 内进行赋值,您可以使用 within。 (在data.frames的情况下,transform也可以。)

包中

不要在 R 包中使用 withhelp(subset) 中有一条警告也适用于 with:

Warning This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences.

如果您使用 with 构建 R 包,当您检查它时,您可能会收到关于使用没有可见绑定的变量的警告或注释。这将使包裹无法被 CRAN 接受。

替代 with

不要使用attach

许多(大部分是过时的)R 教程使用 attach 来避免 re-typing 数据框名称,方法是使列可在全局环境中访问。 attach is widely considered to be bad practice and should be avoided。附加的主要危险之一是,如果单独修改数据列,它们可能会变得不同步。 with 避免了这个陷阱,因为它一次调用一个表达式。 Stack Overflow 上有很多很多问题,其中新用户正在遵循旧教程,并且 运行 由于 attach 而陷入问题。简单的解决方案总是不要使用attach

一直使用with似乎太重复了

如果您要执行多个数据操作步骤,您可能会发现自己的每一行代码都以 with(my_data, ... 开头。您可能认为这种重复几乎与不使用 with 一样糟糕。 data.tabledplyr 包都使用 non-repetitive 语法提供高效的数据操作。我鼓励您学习使用其中之一。两者都有出色的文档。