簡體   English   中英

計算重復測量設計的結果比例

[英]Compute proportion of outcome from repeated measures design

我有以下格式的表格:

CowId    Result          IMI
1        S. aureus       1
1        No growth       0
2        No growth       0
2        No growth       0
3        E. coli         1
3        No growth       0
3        E. coli         0
4        Bacillus sp.    1
4        Contaminated    0

從該表中,我想計算在所有采樣時間點對於 IMI(0 = 負;1 = 正)為負的 CowId 的比例。

在此示例中,25% 的奶牛 [CowId = 2] 在所有采樣時間點的 IMI 測試均為陰性。

為了計算這個比例,我最初的方法是對每個 CowId 進行分組,然后計算負 IMI 數量與 IMI 測試總數之間的差異,其中結果值為 0 表示奶牛對 IMI 完全是陰性的時間點。

到目前為止,我的代碼為每個單獨的 CowId 計算這個。 我怎樣才能增加它來計算上述比例?

fp %>%
  filter(Result != "Contaminated") %>%
  group_by(CowId) %>%
  summarise(negative = (sum(IMI == 0) - length(IMI)))

我們可以計算有多少CowIdall點測試為陰性並計算它們的比率。

library(dplyr)

fp %>%
  filter(Result != "Contaminated") %>%
  group_by(CowId) %>%
  summarise(negative = all(IMI == 0)) %>%
  summarise(total_percent = mean(negative) * 100)

# total_percent
#          <dbl>
#1            25

在基礎 R 中,我們可以使用aggregate

temp <- aggregate(IMI~CowId, subset(fp, Result != "Contaminated"), 
                  function(x) all(x == 0))

mean(temp$IMI) * 100

數據

fp <- structure(list(CowId = c(1L, 1L, 2L, 2L, 3L, 3L, 3L, 4L, 4L), 
Result = structure(c(5L, 4L, 4L, 4L, 3L, 4L, 3L, 1L, 2L), .Label = 
c("Bacillus_sp.","Contaminated", "E.coli", "No_growth", "S.aureus"), 
class = "factor"),IMI = c(1L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L)), 
class = "data.frame", row.names = c(NA, -9L))

帶數據data.table

library(data.table)
setDT(fp)[Result != "Contaminated", .(negative = all(IMI == 0)), 
      .(CowId)][, .(total_percent = mean(negative)* 100 )]
#   total_percent
#1:            25

數據

fp <- structure(list(CowId = c(1L, 1L, 2L, 2L, 3L, 3L, 3L, 4L, 4L), 
Result = structure(c(5L, 4L, 4L, 4L, 3L, 4L, 3L, 1L, 2L), .Label = 
c("Bacillus_sp.","Contaminated", "E.coli", "No_growth", "S.aureus"), 
class = "factor"),IMI = c(1L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L)), 
class = "data.frame", row.names = c(NA, -9L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM