Moo*_*per 4 aggregate r max min factors
我有一个包含因子列的data.frame,我想在其上计算最大值(或最小值或分位数).我不能在因素上使用这些功能,但我想.
这是一些例子:
set.seed(3)
df1 <- data.frame(id = rep(1:5,each=2),height=sample(c("low","medium","high"),size = 10,replace=TRUE))
df1$height <- factor(df1$height,c("low","medium","high"))
df1$height_num <- as.numeric(df1$height)
# > df1
# id height height_num
# 1 1 low 1
# 2 1 high 3
# 3 2 medium 2
# 4 2 low 1
# 5 3 medium 2
# 6 3 medium 2
# 7 4 low 1
# 8 4 low 1
# 9 5 medium 2
# 10 5 medium 2
Run Code Online (Sandbox Code Playgroud)
我可以轻松地做到这一点:
aggregate(height_num ~ id,df1,max)
# id height_num
# 1 1 3
# 2 2 2
# 3 3 2
# 4 4 1
# 5 5 2
Run Code Online (Sandbox Code Playgroud)
但不是这个:
aggregate(height ~ id,df1,max)
# Error in Summary.factor(c(2L, 2L), na.rm = FALSE) :
# ‘max’ not meaningful for factors
Run Code Online (Sandbox Code Playgroud)
我想采用最大的"高度",并在我的聚合表中保持与原始表中相同的级别.在我的真实数据中,我有很多列,我想保持我的因素排序,以保持我的情节清洁和一致.
我可以这样做,并在其他聚合函数中使用以下结构:
use_factors <- function(x,FUN){factor(levels(x)[FUN(as.numeric(x))],levels(x))}
aggregate(height ~ id,df1,use_factors,max)
# id height
# 1 1 high
# 2 2 medium
# 3 3 medium
# 4 4 low
# 5 5 medium
Run Code Online (Sandbox Code Playgroud)
或者我可以超载max min median和quantile我想的功能但是我觉得我肯定会重新发明轮子.
是否有捷径可寻 ?
实际上, 如果使用有序因子,则可以进行所需的聚合.
set.seed(3)
df1 <- data.frame(id = rep(1:5,each=2),height=sample(c("low","medium","high"),size = 10,replace=TRUE))
df1$height <- factor(df1$height,c("low","medium","high"), ordered = TRUE)
df1$height_num <- as.numeric(df1$height)
aggregate(height~id, df1, max)
id height
1 1 high
2 2 medium
3 3 medium
4 4 low
5 5 medium
Run Code Online (Sandbox Code Playgroud)