我需要在分组的数据框中进行汇总(警告:dplyr解决方案非常受欢迎,但不是必需的),包括每个组的某些内容(简单)和“其他”组的相同内容。
最小示例
我在谷歌上搜索了与"dplyr summarize excluding groups"和"dplyr summarize other then group"类似的字符串,我在dplyr文档中搜索,但没有找到解决方案。
这里(如何使用dplyr汇总值不匹配组)不适用,因为它只运行在sum上,即是一个"函数特定"的解决方案(还有一个简单的算术函数,没有考虑每个组的可变性)。对于更复杂的函数请求怎么办(例如mean、sd或用户函数)? :-)
感谢大家
注:
最小示例
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 summarize excluding groups"和"dplyr summarize other then group"类似的字符串,我在dplyr文档中搜索,但没有找到解决方案。
这里(如何使用dplyr汇总值不匹配组)不适用,因为它只运行在sum上,即是一个"函数特定"的解决方案(还有一个简单的算术函数,没有考虑每个组的可变性)。对于更复杂的函数请求怎么办(例如mean、sd或用户函数)? :-)
感谢大家
注:
summarize()
是一个例子,同样的问题也适用于mutate()
或其他基于组工作的dplyr函数。
library(dplyr)
替代前两行代码吗? - Rich Scriven