首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用dplyr "other then“组进行总结

问用dplyr "other then“组进行总结
EN

Stack Overflow用户
提问于 2016-04-06 11:48:54
回答 2查看 2.5K关注 0票数 3

我需要在分组data_frame中进行总结(警告:使用dplyr的解决方案非常受欢迎,但不是强制性的),每个组(简单)和“其他”组上的解决方案都是一样的。

极小例子

代码语言:javascript
复制
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)
    )

我的预期结果如下

代码语言:javascript
复制
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函数。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-04-06 22:35:41

这是我的解决方案:

代码语言:javascript
复制
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])返回了不属于当前组的所有观测值的中值。

我希望这能帮你解决问题。

票数 2
EN

Stack Overflow用户

发布于 2016-04-06 12:06:41

我不认为对summarise()中的其他组执行操作通常是不可能的(也就是说,我认为其他组在总结某个组时是“不可见的”)。您可以定义自己的函数,并在变异中使用它们将它们应用于某个变量。对于更新的示例,可以使用

代码语言:javascript
复制
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.5
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36450278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档