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) |
无论如何,我只是作为练习来做,对我的错误在哪里很好奇。我知道我可以使用匿名函数,但是认为必须有一种使用类似于我最初的非解决方案的语法的方法。我已经浏览了
我刚刚意识到这可行:
1 | lapply(bah,`[[`,i='call') |
还有这个
1 | lapply(bah,function(x)`$`(x,call)) |
也许这只是归因于某些
在
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 formFUN(X[[0L]], , with
...)0L replaced by the current integer index. This is not
normally a problem, but it can be ifFUN usessys.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 foris.numeric
occurs correctly.