【问题标题】:Is there an R function for grouping the data by one variable (column)?是否有用于按一个变量(列)对数据进行分组的 R 函数?
【发布时间】:2019-09-27 07:30:10
【问题描述】:

我测量了细菌对病毒的抑制能力。我有 n 行(个人)和 4 列(a、b、c、x)的数据矩阵。根据 x 列,我想将它们定义为好的或坏的抑制剂。但是,我不确定如何设置 x 列的阈值,具体取决于其他测量的列(a、b、c)。是否有任何 R 函数可以分离/分组我的数据框?

【问题讨论】:

    标签: r grouping


    【解决方案1】:

    在 dplyr 逻辑中有group_by(),它的工作原理是这样的:

    library(dplyr)
    
    df %>%
    group_by(A) %>% # df is now grouped by column A
    summarise(Mean = mean(C)) # calculates the mean of C for each group of A, summarise will delete any other columns not summarised and show only distinct rows
    
    df %>%
    group_by(A) %>%
    mutate(Mean = mean(C)) # This will add the grouped mean to each row without changing the data frame
    

    如果你总结一下,那么你就完成了,但是在 group_by 和 mutate 之后,你必须在某个时候ungroup你的数据框。

    【讨论】:

      【解决方案2】:

      data.table 示例如下。在数据中,我们在 5 个组 (Group) 中有 50 个观察值 (a)。

      数据

      dt = data.table(
        a = runif(1:50),
        Group = sample(LETTERS[1:5], 50, replace = T)
      )
      

      示例 1

      首先,我们可以计算 a 的组均值,如果高于 0.5,则将其标记为“好”,如果低于 0.5,则将其标记为“坏”。请注意,此摘要不包括 a。

      dt1 = dt[, .(Mean = mean(a)), keyby = Group][, Label := ifelse(Mean > 0.5, 'Good', 'Bad')]
      
      > dt1
         Group      Mean Label
      1:     A 0.2982229   Bad
      2:     B 0.4102181   Bad
      3:     C 0.6201973  Good
      4:     D 0.4841881   Bad
      5:     E 0.4443718   Bad
      

      示例 2

      与 Fnguyen 的回答类似,以下代码不会汇总每组的数据;它只会在每个观察值旁边显示组均值和标签。

      dt2 = dt[, Mean := mean(a), by = Group][, Label := ifelse(Mean > 0.5, 'Good', 'Bad')]
      
      > head(dt2)
                 a Group      Mean Label
      1: 0.4253110     E 0.4443718   Bad
      2: 0.4217955     A 0.2982229   Bad
      3: 0.7389260     E 0.4443718   Bad
      4: 0.2499628     E 0.4443718   Bad
      5: 0.3807705     C 0.6201973  Good
      6: 0.2841950     E 0.4443718   Bad
      

      示例 3

      最后,我们当然可以应用条件参数来创建新列,而无需事先计算分组变量。下面的示例测试列 a 和 b 的组合条件。

      dt3 = data.table(a = runif(100), b = runif(100))
      
      dt3[, abGrThan0.5 := ifelse((a > 0.5 & b > 0.5), TRUE, FALSE)]
      
      > head(dt3)
                 a          b abGrThan0.5
      1: 0.5132690 0.02104807       FALSE
      2: 0.8466798 0.96845916        TRUE
      3: 0.5776331 0.79215074        TRUE
      4: 0.9740055 0.59381244        TRUE
      5: 0.4311248 0.07473373       FALSE
      6: 0.2547600 0.09513784       FALSE
      

      【讨论】:

        猜你喜欢
        • 2019-10-05
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多