加上"$"功能 [英] lapply-ing with the "$" function

查看:65
本文介绍了加上"$"功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览哈德利功能指南中的一些示例,并且遇到了意外情况问题.

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)

但是,这些返回null.看来我并没有滥用$函数,因为这些东西起作用了:

However, these return nulls. It seems like I'm not misusing the $ function, as these things work:

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

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

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.

我刚刚意识到这可行:

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

还有这个

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

也许这可以归结为一些需要匿名功能的lapply伏都教徒,而在不需要匿名功能的情况下呢?我觉得以前在SO上的某个地方听说过.

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.

推荐答案

此内容记录在?lapply的注释"部分(重点是我的)中:

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

由于历史原因,lapply创建的呼叫未评估, 并以此为基础编写了代码(例如bquote).这 表示记录的呼叫始终为FUN(X[[0L]], ...)形式,而0L替换为当前的整数索引.这不是 通常是一个问题,但可能是FUN使用sys.call还是 match.call(如果它是使用 .这意味着调用原始函数通常更安全 用包装纸等lapply(ll, function(x) is.numeric(x)) R 2.7.1中需要,以确保is.numeric的方法分派 正确发生.

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.

这篇关于加上"$"功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆