我需要在分组data_frame中进行总结(警告:使用dplyr的解决方案非常受欢迎,但不是强制性的),每个组(简单)和“其他”组上的解决方案都是一样的。
极小例子
if(!require(pacman)) install.packages(pacman)
pacman::p_load(dplyr)
df <- data_frame(
group = c('a', 'a', 'b', 'b', 'c', 'c'),
value = c(1, 2, 3, 4, 5, 6)
)
res <- df %>%
group_by(group) %>%
summarize(
median = median(value)
# median_other = ... ??? ... # I need the median of all "other"
# groups
# median_before = ... ??? ... # I need the median of groups (e.g
# the "before" in alphabetic order,
# but clearly every roule which is
# a "selection function" depending
# on the actual group is fine)
)我的预期结果如下
group median median_other median_before
a 1.5 4.5 NA
b 3.5 3.5 1.5
c 5.5 2.5 2.5我搜索过类似于"dplyr汇总排除组“的Google字符串,"dplyr汇总其他组”,我搜索了dplyr文档,但是我找不到解决方案。
在这里,这个(How to summarize value not matching the group using dplyr)不适用,因为它只运行在和上,即是一个“特定于函数”的解决方案(并且有一个简单的算术函数,它不考虑每个组的可变性)。那么更复杂的函数请求(即均值、sd或用户函数)呢?:-)
感谢所有
PS:summarize()是一个例子,同样的问题会导致mutate()或其他基于组的dplyr函数。
发布于 2016-04-06 22:35:41
这是我的解决方案:
res <- df %>%
group_by(group) %>%
summarise(med_group = median(value),
med_other = (median(df$value[df$group != group]))) %>%
mutate(med_before = lag(med_group))
> res
Source: local data frame [3 x 4]
group med_group med_other med_before
(chr) (dbl) (dbl) (dbl)
1 a 1.5 4.5 NA
2 b 3.5 3.5 1.5
3 c 5.5 2.5 3.5我试图想出一个全dplyr的解决方案,但是基R子集工作得很好,median(df$value[df$group != group])返回了不属于当前组的所有观测值的中值。
我希望这能帮你解决问题。
发布于 2016-04-06 12:06:41
我不认为对summarise()中的其他组执行操作通常是不可能的(也就是说,我认为其他组在总结某个组时是“不可见的”)。您可以定义自己的函数,并在变异中使用它们将它们应用于某个变量。对于更新的示例,可以使用
calc_med_other <- function(x) sapply(seq_along(x), function(i) median(x[-i]))
calc_med_before <- function(x) sapply(seq_along(x), function(i) ifelse(i == 1, NA, median(x[seq(i - 1)])))
df %>%
group_by(group) %>%
summarize(med = median(value)) %>%
mutate(
med_other = calc_med_other(med),
med_before = calc_med_before(med)
)
# group med med_other med_before
# (chr) (dbl) (dbl) (dbl)
#1 a 1.5 4.5 NA
#2 b 3.5 3.5 1.5
#3 c 5.5 2.5 2.5https://stackoverflow.com/questions/36450278
复制相似问题