首页 > 解决方案 > 仅在 R 中对疑似类别的患者进行了多少次测试

问题描述

我有可重复的例子。我有重复的 ID。有些怀疑有些没有。

structure(list(id = c(1, 1, 1, 2, 2, 3, 3, 4, 4, 4), test = c("susp", 
"susp", "neg", "pos", "pos", "neg", "pos", "susp", "susp", "neg"
)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))

然而,我有兴趣得到计数:

  1. 疑似患者总数

  2. 那些怀疑无论结果如何都进行了多次测试的客户。

  3. 想把那些有两个和三个嫌疑人的总数统计一下。

警告!如果这可以用 tidyverse 来完成,那就太棒了。表格的外观示例,请参见下文。

structure(list(id = c(1, 4), number_of_test_for_suspected_pat = c(2, 
2)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
))

并且附加tibble共对疑似患者进行后续检测。

标签: rcountduplicatestidyverse

解决方案


我们可以filter输出没有任何“疑似”病例的“id”,然后得到sum逻辑向量

library(dplyr)
df1 %>%
    group_by(id) %>% 
    filter('susp' %in% test) %>% 
    summarise(number_of_test_for_suspected_pat = sum(test == 'susp'),
    n_greater_than_3 = number_of_test_for_suspected_pat >=3) %>%
     mutate(Total = sum(number_of_test_for_suspected_pat), 
         n_greater_than_3_count = sum(n_greater_than_3))
# A tibble: 2 x 5
#     id number_of_test_for_suspected_pat n_greater_than_3 Total n_greater_than_3_count
#  <dbl>                            <int> <lgl>            <int>                  #<int>
#1     1                                2 FALSE                4                      0
#2     4                                2 FALSE                4                      0

或者做第filter一个

df1 %>%
   filter(test == 'susp') %>%
   count(id) %>%
   mutate(Total = sum(n))

推荐阅读