[英]lapply-ing with the “$” function
I was going through some examples in hadley's guide to functionals, and came across an unexpected problem. 我正在浏览哈德利函数指南中的一些示例 ,并遇到了意外问题。
Suppose I have a list of model objects, 假设我有一个模型对象列表,
x=1:3;y=3:1; bah <- list(lm(x~y),lm(y~x))
and want to extract something from each (as suggested in hadley's question about a list called "trials"). 并希望从每个示例中提取一些内容(如哈德利关于列表“试验”的问题所建议)。 I was expecting one of these to work: 我期望其中之一可以工作:
lapply(bah,`$`,i='call') # or...
lapply(bah,`$`,call)
However, these return nulls. 但是,这些返回空值。 It seems like I'm not misusing the $
function, as these things work: 似乎我没有滥用$
函数,因为这些东西起作用:
`$`(bah[[1]],i='call')
`$`(bah[[1]],call)
Anyway, I'm just doing this as an exercise and am curious where my mistake is. 无论如何,我只是作为练习来做,对我的错误在哪里很好奇。 I know I could use an anonymous function, but think there must be a way to use syntax similar to my initial non-solution. 我知道我可以使用匿名函数,但认为必须有一种使用类似于我最初的非解决方案的语法的方法。 I've looked through the places $
is mentioned in ?Extract
, but didn't see any obvious explanation. 我已经看过$
?Extract
提到$
的地方,但是没有看到任何明显的解释。
I just realized that this works: 我刚刚意识到这可行:
lapply(bah,`[[`,i='call')
and this 和这个
lapply(bah,function(x)`$`(x,call))
Maybe this just comes down to some lapply
voodoo that demands anonymous functions where none should be needed? 也许这只是归结为一些lapply
伏都lapply
,他们需要匿名函数而无需使用匿名函数吗? I feel like I've heard that somewhere on SO before. 我觉得我以前在某处听说过。
This is documented in ?lapply
, in the "Note" section (emphasis mine): 在?lapply
的“注释”部分(强调我的部分)中?lapply
进行了记录:
For historical reasons, the calls created by
lapply
are unevaluated, and code has been written (egbquote
) that relies on this. 由于历史原因,lapply
创建的调用未进行lapply
,并且已经编写了依赖此的代码(例如bquote
)。 This means that the recorded call is always of the formFUN(X[[0L]], ...)
, with0L
replaced by the current integer index. 这意味着记录的呼叫始终为FUN(X[[0L]], ...)
,其中0L
替换为当前整数索引。 This is not normally a problem, but it can be ifFUN
usessys.call
ormatch.call
or if it is a primitive function that makes use of the call. 通常这不是问题,但是如果FUN
使用sys.call
或match.call
或者它是利用该调用的原始函数,则可能会出现问题。 This means that it is often safer to call primitive functions with a wrapper, so that eglapply(ll, function(x) is.numeric(x))
is required in R 2.7.1 to ensure that method dispatch foris.numeric
occurs correctly. 这意味着用包装器调用原始函数通常更安全,因此在R 2.7.1中需要lapply(ll, function(x) is.numeric(x))
以确保为is.numeric
方法分派。正确地。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.