与"$"一起使用功能 [英] lapply with "$" function
问题描述
假设我有一个data.frames列表
Let's say I have a list of data.frames
dflist <- list(data.frame(a=1:3), data.frame(b=10:12, a=4:6))
如果我想从列表中的每个项目中提取第一列,我可以做
If i want to extract the first column from each item in the list, I can do
lapply(dflist, `[[`, 1)
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] 10 11 12
为什么我不能以相同的方式使用"$"功能
Why can't I use the "$" function in the same way
lapply(dflist, `$`, "a")
# [[1]]
# NULL
#
# [[2]]
# NULL
但是这些都可以工作:
lapply(dflist, function(x) x$a)
`$`(dflist[[1]], "a")
我意识到在这种情况下,可以使用
I realize that in this case one could use
lapply(dflist, `[[`, "a")
但是我正在使用一个S4对象,该对象似乎不允许通过[[
进行索引.例如
but I was working with an S4 object that didn't seem to allow indexing via [[
. For example
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
推荐答案
对于第一个示例,您可以执行以下操作:
For the first example, you can just do:
lapply(dflist, `$.data.frame`, "a")
第二次使用slot()
访问器功能
lapply(mylist, "slot", "tab")
我不确定为什么在第一种情况下不起作用,但是?lapply
的Note
部分确实解决了其为原始函数分配的烦人方法的问题就像$
:
I'm not sure why method dispatch doesn't work in the first case, but the Note
section of ?lapply
does address this very issue of its borked method dispatch for primitive functions like $
:
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.
这篇关于与"$"一起使用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!