gpt4 book ai didi

r - lapply 与 "$"函数

转载 作者:行者123 更新时间:2023-12-03 07:34:56 26 4
gpt4 key购买 nike

假设我有一个 data.frames 列表

dflist <- list(data.frame(a=1:3), data.frame(b=10:12, a=4:6))

如果我想从列表中的每个项目中提取第一列,我可以这样做

lapply(dflist, `[[`, 1)
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] 10 11 12

为什么我不能以同样的方式使用“$”函数

lapply(dflist, `$`, "a")
# [[1]]
# NULL
#
# [[2]]
# NULL

但这两个都有效:

lapply(dflist, function(x) x$a)
`$`(dflist[[1]], "a")

我意识到在这种情况下可以使用

lapply(dflist, `[[`, "a")

但我正在使用一个 S4 对象,该对象似乎不允许通过 [[ 进行索引。例如

library(adegenet)
data(nancycats)
catpop <- genind2genpop(nancycats)
mylist <- list(catpop, catpop)

#works
catpop[[1]]$tab

#doesn't work
lapply(mylist, "$", "tab")
# Error in slot(x, name) :
# no slot of name "..." for this object of class "genpop"

#doesn't work
lapply(mylist, "[[", "tab")
# Error in FUN(X[[1L]], ...) : this S4 class is not subsettable

最佳答案

对于第一个示例,您可以这样做:

lapply(dflist, `$.data.frame`, "a")

对于第二个,使用 slot() 访问器函数

lapply(mylist, "slot", "tab")
<小时/>

我不确定为什么方法分派(dispatch)在第一种情况下不起作用,但 ?lapplyNote 部分确实解决了对于像 $ 这样的原始函数来说,它的 borked 方法调度就是这个问题:

 Note:

[...]

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[[i]], ...)’, with ‘i’ replaced by the current
(integer or double) 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 to ensure
that method dispatch for ‘is.numeric’ occurs correctly.

关于r - lapply 与 "$"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30131542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com