使用plyr按类别计算最频繁的级别

2023-12-12

我想使用下面的代码使用 plyr 按类别计算最常见的因子级别。数据框b显示请求的结果。为什么c$mlevels只有“数字”值吗?

require(plyr)
set.seed(0)
a <- data.frame(cat=round(runif(100, 1, 3)),
                levels=factor(round(runif(100, 1, 10))))
mode <- function(x) names(table(x))[which.max(table(x))]
b <- data.frame(cat=1:3,
                mlevels=c(mode(a$levels[a$cat==1]),
                       mode(a$levels[a$cat==2]),
                       mode(a$levels[a$cat==3])))
c <- ddply(a, .(cat), summarise,
           mlevels=mode(levels))

当你使用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 处获取。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用plyr按类别计算最频繁的级别 的相关文章

随机推荐