lapply-ing with the “$” function

被刻印的时光 ゝ 提交于 2019-11-26 11:38:01

问题


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.

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? I feel like I\'ve heard that somewhere on SO before.


回答1:


This is documented in ?lapply, in the "Note" section (emphasis mine):

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.



来源:https://stackoverflow.com/questions/18216084/lapply-ing-with-the-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!