【问题标题】:R: How to substract values depending on factor levels on multiple columns?R:如何根据多列的因子水平减去值?
【发布时间】:2017-09-05 14:11:39
【问题描述】:

我有一个看起来像这样的数据框(使用 reshape2::cast 和合并):

time days treatment extrafactor1 extrafactor2 extrafactor3 animal1  animal2 animal3
10  83  control B   water   2   2   67  40
10  83  control B   water   3   50  67  39
10  83  control A   water   3   22  80  63
10  83  control A   water   2   40  40  100
10  83  treated A   water   3   40  69  92
10  83  treated A   water   1   64  56  6
10  83  treated A   water   2   90  67  52
10  83  treated B   water   2   14  36  77
10  83  treated B   water   3   41  83  55
10  83  treated B   water   1   66  31  51
11  86  control B   water   1   99  100 10
11  86  control B   water   2   23  27  22
11  86  control A   water   3   57  10  65
11  86  control A   water   1   60  2   49
11  86  control A   water   2   23  14  44
11  86  control B   water   3   97  45  20
11  86  treated B   water   2   71  15  24
11  86  treated B   water   3   49  55  63
11  86  treated A   water   3   54  88  27

我想从处理过的样本中减去对照样本中不同动物的值。当然,减法应在其他因素的水平匹配时进行,因此“11_86_treatment_A_water_3”的animal1-value应减去“11_86_control_A_water_3”的animal1-value,这适用于每只动物。我一直在用 plyr 尝试一些事情,比如

df2 <- ddply(df, .(time,days,treatment,extrafactor1,extrafactor2,extrafactor3), transform, animal1 = animal1-animal1[treatment=="control"])

但它给了我很多 NA,我确信缺少信息来充分执行我想要的。实际上有 100 多种动物。

我的尝试是从这里改编的,但是输入变量和要执行的列更少:Easiest way to subtract associated with one factor level from values associated with all other factor levels 在这里:R ddply with multiple variables

也可以等到将表格重新整形为ggplot的长格式,如果这样会让事情变得更容易?

你对我有什么建议吗?

【问题讨论】:

标签: r plyr reshape


【解决方案1】:

不是最优雅的,但您可以创建一个名为 group_string 的新列,它是您在示例中已经提到的所有不同因素的连接字符串。但它是“控制”还是“治疗”将是最后一个论点。例如,而不是

"11_86_treated_A_water_3""11_86_control_A_water_3"

你会有

"11_86_A_water_3_treated""11_86_A_water_3_control"

然后您可以在没有处理/控制子字符串的情况下对所有唯一字符串运行循环,例如一个唯一的字符串是"11_86_A_water_3_",对于每个字符串,从group_string 中“处理”的行中减去group_string 中具有“控制”的行。

编辑: 好的,刚刚有了另一个想法。 按除治疗(时间、天数、extrafactor1、extrafactor2、extrafactor3)之外的所有因素进行分组,这应该为每个子组留出两行。然后使用diff() 计算每个子组的这两行之间的差异。

【讨论】:

  • 嘿 Elevendollar,非常感谢您的意见...在类似的情况下,我已经多次使用连接,我只是认为会有更优雅的方式 ;-) 我会让你知道它什么时候起作用
  • 嘿@crazysantaclaus。肯定的事。查看可重现的示例链接。如果您相应地编辑您的问题,我相信有人会提供帮助。
猜你喜欢
  • 1970-01-01
  • 2019-08-06
  • 2023-03-06
  • 2021-01-15
  • 2016-03-06
  • 1970-01-01
  • 2019-03-18
  • 2017-11-29
  • 1970-01-01
相关资源
最近更新 更多