Summarize with dplyr “other then” groups

后端 未结 2 778
感情败类
感情败类 2021-01-20 14:38

I need to summarize in a grouped data_frame (warn: a solution with dplyr is very much appreciated but isn\'t mandatory) both something on each group (simple) and the same so

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 15:03

    Here's my solution:

    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
    

    I was trying to come up with an all-dplyr solution but base R subsetting works just fine with median(df$value[df$group != group]) returning the median of all observations that are not in the current group.

    I hope this help you to solve your problem.

提交回复
热议问题