【问题标题】:Get relative abundance of each group dplyr获取每组 dplyr 的相对丰度
【发布时间】:2020-06-20 14:08:38
【问题描述】:

我有以下小标题:

 dd <- structure(list(group_members = structure(c(6L, 6L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 5L, 5L),
 .Label = c("1", "2", "3", "4", "5", ">6"), class = "factor"), Test_A = c("negative", "positive",
 "negatiu", "positive", "negatiu", "positive", "negatiu", "positive", "negatiu", "positive", "negatiu", "positive"), cases = c(58L, 2L, 14781L, 3525L, 7867L, 415L, 4113L, 72L, 2054L, 10L, 347L, 2L)), row.names = c(NA, -12L), groups = structure(list(group_members = structure(1:6, .Label = c("1", "2", "3", "4", "5", ">6"), class = "factor"), .rows = structure(list( 3:4, 5:6, 7:8, 9:10, 11:12, 1:2), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), row.names = c(NA, 6L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", "data.frame"))

这是小标题

> dd
# A tibble: 12 x 3
# Groups:   group_members [6]
   group_members Test_A   cases
   <fct>         <chr>    <int>
 1 >6            negative    58
 2 >6            positive     2
 3 1             negatiu  14781
 4 1             positive  3525
 5 2             negatiu   7867
 6 2             positive   415
 7 3             negatiu   4113
 8 3             positive    72
 9 4             negatiu   2054
10 4             positive    10
11 5             negatiu    347
12 5             positive     2

我想要每个组的相对丰富度。例如对于“group_members >6”,我有 58 个阴性病例和 2 个阳性病例。我想得到一个新的专栏如下:

以 group6 为例:“Frequency= 58/60=0.96 and "Frequency= 2/60=0.04" "

> dd
    # A tibble: 12 x 3
    # Groups:   group_members [6]
       group_members Test_A   cases  frequency
       <fct>         <chr>    <int>
     1 >6            negative    58  0.96
     2 >6            positive     2   0.004
.....

感谢您的帮助。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:
    dd %>%
      group_by(group_members) %>%
      mutate(frequency = cases / sum(cases))
    

    给予:

    # A tibble: 12 x 4
    # Groups:   group_members [6]
       group_members Test_A   cases frequency
       <fct>         <chr>    <int>     <dbl>
     1 >6            negative    58   0.967  
     2 >6            positive     2   0.0333 
     3 1             negatiu  14781   0.807  
     4 1             positive  3525   0.193  
     5 2             negatiu   7867   0.950  
     6 2             positive   415   0.0501 
     7 3             negatiu   4113   0.983  
     8 3             positive    72   0.0172 
     9 4             negatiu   2054   0.995  
    10 4             positive    10   0.00484
    11 5             negatiu    347   0.994  
    12 5             positive     2   0.00573
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      相关资源
      最近更新 更多