【问题标题】:R Summarise dplyr grouped data with certain rows excluded based on another columnR总结基于另一列排除某些行的dplyr分组数据
【发布时间】:2018-11-15 01:07:47
【问题描述】:

我想根据单独分组变量列中具有特定值的所有行行来汇总多列数据。例如,在下面的 df 中,我想根据未分配给与给定行匹配的集群的行的值来获取 A、B、C、D 和 E 的中值。

df = data.frame(cluster = c(1:5, 1:3, 1:2),
                    A = rnorm(10, 2),
                    B = rnorm(10, 5),
                    C = rnorm(10, 0.4),
                    D = rnorm(10, 3),
                    E = rnorm(10, 1))

df %>%
group_by(cluster) %>%
summarise_at(toupper(letters[1:5]), funs(m = fun_i_need_help_with(.)))

fun_i_need_help_with 相当于:

    first row: median(df[which(df$cluster != 1), "A"])
    second row: median(df[which(df$cluster != 2), "A"])
    and so on...

我可以使用嵌套的 for 循环来做到这一点,但它运行起来很慢,而且似乎不是一个好的类似 R 的解决方案。

for(col in toupper(letters[1:5])){
    for(clust in unique(df$cluster)){
        df[which(df$cluster == clust), col] <-
           median(df[which(df$cluster != clust), col])
     }
    }

【问题讨论】:

  • 随机注:LETTERS[1:5]toupper(letters[1:5])相同
  • 谢谢,很高兴知道!

标签: r dplyr


【解决方案1】:

使用tidyverse 的解决方案。

set.seed(123)

df = data.frame(cluster = c(1:5, 1:3, 1:2),
                A = rnorm(10, 2),
                B = rnorm(10, 5),
                C = rnorm(10, 0.4),
                D = rnorm(10, 3),
                E = rnorm(10, 1))

library(tidyverse)

df2 <- map_dfr(unique(df$cluster),
        ~df %>%
          filter(cluster != .x) %>%
          summarize_at(vars(-cluster), funs(median(.))) %>%
          # Add a label to show the content of this row is not from a certain cluster number
          mutate(not_cluster = .x))
df2
#          A        B          C        D         E not_cluster
# 1 2.070508 5.110683  0.1820251 3.553918 0.7920827           1
# 2 2.070508 5.400771 -0.6260044 3.688640 0.5333446           2
# 3 1.920165 5.428832 -0.2769652 3.490191 0.8543568           3
# 4 1.769823 5.400771 -0.2250393 3.426464 0.5971152           4
# 5 1.769823 5.400771 -0.3288912 3.426464 0.5971152           5

【讨论】:

  • 谢谢,这完全符合我的期望。我必须阅读一些有关 map_dfr 的内容,以便我真正了解那里发生的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多