当你使用summarise
, plyr
在检查函数之前似乎“看不到”在全局环境中声明的函数base
:
我们可以使用 Hadley's Handy 来检查这一点pryr
包裹。您可以通过以下命令安装它:
library(devtools)
install_github("pryr")
require(pryr)
require(plyr)
c <- ddply(a, .(cat), summarise, print(where("mode")))
# <environment: namespace:base>
# <environment: namespace:base>
# <environment: namespace:base>
基本上,它不会读/知道/看到your mode
功能。有two备择方案。第一个是@AnandaMahto 的建议,我也会这样做,并建议你坚持下去。另一种选择是不使用summarise
并使用调用它function(.)
所以这样mode
您的全球环境中的功能是“可见的”。
c <- ddply(a, .(cat), function(x) mode(x$levels))
# cat V1
# 1 1 6
# 2 2 5
# 3 3 9
为什么这有效?
c <- ddply(a, .(cat), function(x) print(where("mode")))
# <environment: R_GlobalEnv>
# <environment: R_GlobalEnv>
# <environment: R_GlobalEnv>
因为正如您在上面看到的,它读取位于global environment
.
> mode # your function
# function(x)
# names(table(x))[which.max(table(x))]
> environment(mode) # where it sits
# <environment: R_GlobalEnv>
与以下相反:
> base::mode # base's mode function
# function (x)
# {
# some lines of code to compute mode
# }
# <bytecode: 0x7fa2f2bff878>
# <environment: namespace:base>
这是一个很棒的维基 on environments
如果您有兴趣进一步阅读/探索,请从 Hadley 处获取。