【问题标题】:count total and positive samples by group按组计算总样本和正样本
【发布时间】:2018-07-07 02:30:23
【问题描述】:

我有一个这样的数据框;

df <- data.frame(concentration=c(0,0,0,0,2,2,2,2,4,4,6,6,6),
             result=c(0,0,0,0,0,0,1,0,1,0,1,1,1))

我想计算每个浓度水平的结果总数。 我想计算每个浓度水平的阳性样本数。 我想创建一个具有集中度、总结果和阳性数的新数据框。

conc pos_c total_c
0    0     4
2    1     4
4    1     2
6    3     3

这是我迄今为止使用 plyr 想出的;

c <- count(df, "concentration")
r <- count(df, "concentration","result")
names(c)[which(names(c) == "freq")] <- "total_c"
names(r)[which(names(r) == "freq")] <- "pos_c"
cbind(c,r)

  concentration total_c concentration pos_c
1             0       4             0     0
2             2       4             2     1
3             4       2             4     1
4             6       3             6     3

重复浓度列。我认为可能有一种更好/更简单的方法可以做到这一点,我错过了。也许另一个图书馆。我不确定如何在 R 中做到这一点,这对我来说相对较新。谢谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    我们需要sum 的群组。使用tidyverse,我们按'浓度(group_by)分组,然后summarise得到两列 - 1)sum的逻辑表达式(result &gt; 0),2)行数(n() )

    library(dplyr)
    df %>% 
      group_by(conc = concentration) %>% 
      summarise(pos_c = sum(result > 0), # in the example just sum(result) 
                        total_c = n())
    # A tibble: 4 x 3
    #   conc pos_c total_c
    #  <dbl> <int>   <int>
    #1     0     0       4
    #2     2     1       4
    #3     4     1       2
    #4     6     3       3
    

    或将base Rtableaddmargins 一起使用

    addmargins(table(df), 2)[,-1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2022-11-13
      • 1970-01-01
      相关资源
      最近更新 更多