2016-02-10 26 views
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?

+5

有点基于意见,但基本上我会说部分匹配是主​​要的危险。 –

+4

当你知道名字的时候''''很好。问题是当人们试图在动态代码中使用'$'时,例如'col =“mpg”; mtcars $关口; mtcars [COL]'。这是什么'幸运(312)'意味着什么时候说*名字存储在y *中的列。如果该列名为'“y”',那么'x $ y'就好了,但如果'y'是一个包含列名字符串表示形式的变量,那么'$'将不起作用,您需要使用'['或'[['。 – Gregor

+0

'$'用于交互式使用。文档中的第二个引用解释了程序使用中的潜在问题。也就是说,我从来没有遇到过严重的问题。 – Roland

回答

2

考虑名单:

foo<-list(BlackCat=1,BlackDog=2, WhiteCat=3,WhiteDog=4) 

假设你要根据两个用户参数变量调用指数之:颜色和动物物种。 代码Parametrising颜色和种类的地方作为

myColour<-"Black" 
mySpecies<-"Dog" 

您可以通过使用[[[拨打电话索引参数容易地

foo[[paste0(myColour,mySpecies)]] 

。但是,$提取不是这种情况:foo $ paste0(myColour,mySpecies)不会评估函数paste0