关于r:应用“ $”功能

lapply-ing with the “$” function

我正在查看哈德利函数指南中的一些示例,并遇到了意外问题。

假设我有一个模型对象列表,

1
x=1:3;y=3:1; bah <- list(lm(x~y),lm(y~x))

并希望从每个示例中提取一些信息(如哈德利关于列表"试验"的问题所建议)。我期望其中之一可以工作:

1
2
lapply(bah,`$`,i='call') # or...
lapply(bah,`$`,call)

但是,这些返回空值。看来我没有滥用$函数,因为这些东西可以正常工作:

1
2
`$`(bah[[1]],i='call')
`$`(bah[[1]],call)

无论如何,我只是作为练习来做,对我的错误在哪里很好奇。我知道我可以使用匿名函数,但是认为必须有一种使用类似于我最初的非解决方案的语法的方法。我已经浏览了?Extract中提到的$的地方,但是没有看到任何明显的解释。

我刚刚意识到这可行:

1
lapply(bah,`[[`,i='call')

还有这个

1
lapply(bah,function(x)`$`(x,call))

也许这只是归因于某些lapply伏都教徒,他们需要不需要匿名功能的匿名功能?我觉得以前在SO上的某个地方听说过。


?lapply的"注释"部分(重点是我的)中对此进行了记录:

For historical reasons, the calls created by lapply are unevaluated,
and code has been written (e.g. bquote) that relies on this. This
means that the recorded call is always of the form FUN(X[[0L]],
...)
, with 0L replaced by the current integer index. This is not
normally a problem, but it can be if FUN uses sys.call or
match.call or if it is a primitive function that makes use of the
call. This means that it is often safer to call primitive functions
with a wrapper, so that e.g. lapply(ll, function(x) is.numeric(x))
is required in R 2.7.1 to ensure that method dispatch for is.numeric
occurs correctly.