【问题标题】:Subtracting the response of the "control" to all other groups减去“控制”对所有其他组的响应
【发布时间】:2018-10-12 01:36:31
【问题描述】:

我进行了多次重复测量的治疗, 我想减去每次治疗的每个时间点的对照值。 数据集的形状是这样的,有多年、物种和治疗。

 ID Year Species Treatment value
 1  2010  x       control   0.04
 1  2011  x       control   0.10
 2  2010  x       MaxDamage 0.02
 2  2011  x       MaxDamage 0.06

我想添加一列

 difference =( value of the Treatment for each year - value of the control for each year)

 ID Year Species Treatment value  difference
 1  2010  x       control   0.04   0
 1  2011  x       control   0.1    0
 2  2010  x       MaxDamage 0.02  -0.02
 2  2011  x       MaxDamage 0.06  -0.04

欢迎提出任何建议, 谢谢你

【问题讨论】:

    标签: r grouping


    【解决方案1】:

    我们可以按'Year'分组,然后将'value'列和'Treatment'对应的'value'的差值作为“对照”

    library(dplyr)
    df1 %>%
       group_by(Year) %>%
       mutate(difference = value - value[Treatment == "control"])
    # A tibble: 4 x 6
    # Groups:   Year [2]
    #     ID  Year Species Treatment value difference
    #  <int> <int> <chr>   <chr>     <dbl>      <dbl>
    #1     1  2010 x       control    0.04       0   
    #2     1  2011 x       control    0.1        0   
    #3     2  2010 x       MaxDamage  0.02      -0.02
    #4     2  2011 x       MaxDamage  0.06      -0.04
    

    如果'control'出现的顺序和每个'Year'有两个'Treatment'一样,那么我们可以不分组,而是对'value'进行子集化,然后直接做差异

    df1 %>%
        mutate(difference = value - rep(value[Treatment == "control"], ceiling(n()/2)))
    

    【讨论】:

      【解决方案2】:

      您可以加入包含控制值的表:

      library(data.table)
      setDT(DF)
      
      DF[
        DF[Treatment == "control", .(Year, c_value = value)], 
        on=.(Year), 
        d := value - c_value
      ][]
      
      # or
      library(dplyr)
      
      left_join(DF, 
        DF %>% filter(Treatment == "control") %>% select(Year, c_value = value)
      ) %>% mutate(d = value - c_value) %>% select(-c_value)
      

      data.table方式修改DF,而dplyr新建表。

      使用的数据:

      DF = structure(list(ID = c(1L, 1L, 2L, 2L), Year = c(2010L, 2011L, 
      2010L, 2011L), Species = c("x", "x", "x", "x"), Treatment = c("control", 
      "control", "MaxDamage", "MaxDamage"), value = c(0.04, 0.1, 0.02, 
      0.06)), .Names = c("ID", "Year", "Species", "Treatment", "value"
      ), row.names = c(NA, -4L), class = "data.frame")
      

      【讨论】:

      • data.table 选项非常简洁,我希望如此!谢谢!
      猜你喜欢
      • 2022-01-14
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多