【问题标题】:Calculate proportions within groups in a data frame in R计算R中数据框中组内的比例
【发布时间】:2020-10-19 18:57:42
【问题描述】:

我在 R 中有以下数据框。对于这个实验,我用 2 次处理多次测试细胞的存活率,每次处理 2 次重复。我想计算每次处理/重复每次存活细胞的百分比。

例如,Treat 1 Rep 1 为 500/500、470/500、100/500、20/500,Treat 2 Rep 1 为 430/430、420/430、300/430、 100/430

谢谢!

x <- data.frame("treatment"= c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2),
                "rep"=c(1,1,1,1,2,2,2,2,1,1,1,1,2,2,2,2),
                "Time" = c(0, 30, 60, 180, 0, 30, 60, 180, 0, 30, 60, 180,0, 30, 60, 180 ), 
                "cells_alive" = c(500, 470, 100, 20, 476, 310, 99, 2, 430, 420, 300, 100, 489, 451, 289, 4))

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    我们可以按'treatment'、'rep'分组,用'cells_alive'除以'time'对应的'cells_alive'值为0来计算'prop'ortion

    library(dplyr)
    x1 <- x %>% 
       group_by(treatment, rep) %>% 
       mutate(prop = cells_alive/cells_alive[Time == 0])
    

    -输出

    x1
    # A tibble: 16 x 5
    # Groups:   treatment, rep [4]
    #   treatment   rep  Time cells_alive    prop
    #       <dbl> <dbl> <dbl>       <dbl>   <dbl>
    # 1         1     1     0         500 1      
    # 2         1     1    30         470 0.94   
    # 3         1     1    60         100 0.2    
    # 4         1     1   180          20 0.04   
    # 5         1     2     0         476 1      
    # 6         1     2    30         310 0.651  
    # 7         1     2    60          99 0.208  
    # 8         1     2   180           2 0.00420
    # 9         2     1     0         430 1      
    #10         2     1    30         420 0.977  
    #11         2     1    60         300 0.698  
    #12         2     1   180         100 0.233  
    #13         2     2     0         489 1      
    #14         2     2    30         451 0.922  
    #15         2     2    60         289 0.591  
    #16         2     2   180           4 0.00818
    

    match

    x %>%
         group_by(treatment, rep) %>%
         mutate(prop = cells_alive/cells_alive[match(0, Time)])
    

    如果“时间”已经订好了

    x %>%
         group_by(treatment, rep) %>%
         mutate(prop = cells_alive/first(cells_alive))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多