0
fortune(312)
和fortune(343)
暗示了使用$
来提取列表中的元素而不是[[
的问题,但没有具体说明究竟是什么危险。
The problem here is that the $ notation is a magical shortcut and like any other magic
if used incorrectly is likely to do the programmatic equivalent of turning yourself into
a toad.
-- Greg Snow (in response to a user that wanted to access a column whose name is stored
in y via x$y rather than x[[y]])
R-help (February 2012)
Sooner or later most R beginners are bitten by this all too convenient shortcut. As an R
newbie, think of R as your bank account: overuse of $-extraction can lead to undesirable
consequences. It's best to acquire the '[[' and '[' habit early.
-- Peter Ehlers (about the use of $-extraction)
R-help (March 2013)
通过对`$`
的文档看,我发现
$仅适用于递归对象
和
的主要区别在于, $不允许计算索引,而[[] [...]还有部分匹配行为o f [[可以使用确切的参数进行控制。
那么,是使用[[
在$
的说法,因为在编写代码前提供更大的控制和透明度?使用$
的实际风险是什么,如果[[
是首选,那么在任何情况下,它的是适合使用$
-extraction?
有点基于意见,但基本上我会说部分匹配是主要的危险。 –
当你知道名字的时候''''很好。问题是当人们试图在动态代码中使用'$'时,例如'col =“mpg”; mtcars $关口; mtcars [COL]'。这是什么'幸运(312)'意味着什么时候说*名字存储在y *中的列。如果该列名为'“y”',那么'x $ y'就好了,但如果'y'是一个包含列名字符串表示形式的变量,那么'$'将不起作用,您需要使用'['或'[['。 – Gregor
'$'用于交互式使用。文档中的第二个引用解释了程序使用中的潜在问题。也就是说,我从来没有遇到过严重的问题。 – Roland