如何通过在另一列 r 中使用多个变量来改变新列

How to mutate new column by using multiple variable's in another column r

您好,我想使用 mutate 函数创建一个新变量 Foldchange。但是我想使用同一列中的值来计算它。有没有什么方法可以计算一个新变量,从同一列中折叠变化而不重新排列 table,这样 table 就不需要拆分了?

为了清楚起见,这里有一个例子:

  Plate Sample_ID Visit  Bead_MFI Phago_Score mean_phago
 <fct> <chr>     <fct>        <int>       <dbl>      <dbl>
 4     100004    V1            1199        237.       253.
 4     100077    V1            1522        405.       396.
 4     100077    V2            1349        324.       814.
 4     100004    V2            1518        466.       867

我想要的输出类似于使用:

test %>% group_by("Sample", "Plate") %>% mutate (Foldchange = ((mean_phago$V2-mean_phago$V1)/mean_phago$V1))

得到

Plate Sample_ID Visit  Bead_MFI Phago_Score mean_phago  Foldchange 
 <fct> <chr>     <fct>        <int>       <dbl>      <dbl>
 4     100004    V1            1199        237.       253.  2.42
 4     100077    V1            1522        405.       396.  1.11
 4     100077    V2            1349        324.       834.  1.11
 4     100004    V2            1518        466.       867   2.42

显然我不能 select 使用此代码基于 V1 和 V2 变量,但这只是为了说明。我希望通过这种方式我可以保持我的额外 table 完好无损,折叠变化会有重复的值,但在这一点上没关系。

感谢您提前提供的帮助,对 R 还是很陌生!

马里

我们需要根据逻辑条件进行子集化

library(dplyr)
test %>% 
    group_by(Plate) %>%
    mutate(Foldchange =  (mean_phage[Visit == 'V2'] - 
          mean_phage[Visit == 'V1'])/mean_phage[Visit =='V1']) 

或者如果每组只有一个'V1'、'V2',可以使用diff

test %>% 
    arrange(Plate, desc(Visit)) %>%
    group_by( Plate) %>%
    mutate(Foldchange = diff(mean_phage)/last(mean_phage))