【问题标题】:find groups represented in multiple tests查找在多个测试中表示的组
【发布时间】:2018-06-04 04:15:09
【问题描述】:

在 R 数据框中,我有在三个条件之一下发生的事件对,并希望找到在每个条件下发生的那些对。例如:

label1   label2   factor  value
 bob      ted        A     4
 bob     carol       A     3
 ted     carol       A     2
 bob      ted        B     3
 ted     carol       B     4
 bob      ted        C     2
 bob     carol       C     9
 ted     carol       C     6

我如何获得在所有三个因素中都有条目的那些对的平均值?

bob      ted         (4+3+2)/3 = 3
ted     carol        (2+4+6)/3 = 4

没有为“bob”和“carol”这对计算任何内容,因为该对没有因子 B 的值。主要问题是如何识别在每个因子中具有值的那些对。

【问题讨论】:

    标签: r dataframe unique


    【解决方案1】:

    使用dplyr,我们可以group_by label1 和label2 并仅过滤那些all 值为“A”、“B”和“C”的组,然后取mean那些团体。

    library(dplyr)
    df %>%
      group_by(label1, label2) %>%
      filter(all(c("A", "B", "C") %in% factor)) %>%
      summarise(avg = mean(value))
    
    # label1 label2   avg
    #  <fct>  <fct>  <dbl>
    #1 bob    ted     3.00
    #2 ted    carol   4.00
    

    或者如果我们不想对这些值进行硬编码,我们可以在之前获得unique。

    unique_value <- unique(df$factor)
    
    df %>%
      group_by(label1, label2) %>%
      filter(all(unique_value %in% factor)) %>%
      summarise(avg = mean(value))
    

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 2017-10-19
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 2022-08-15
      • 2016-02-11
      • 1970-01-01
      • 2012-04-10
      相关资源
      最近更新 更多