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

Viewed 108

Hi I would like to make a new variable, Foldchange, by using the mutate function. However I want to calculate this using values from the same column. Is there any way to calculate a new variable, fold change from within the same column without rearranging the table so that the table doesn't require splitting up?

Here is an example for clarity:

  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

the output I would like is something like using:

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

to get

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

Obviously I cant select based the V1 and V2 variables using this code but that's just to illustrate. I'm hoping through this way I can keep my additional table in tact, the fold change would have repeating values but that's OK at this point.

Thanks for any help in advance still quite new to R!

Mari

1 Answers

We need to subset based on a logical condition

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

Or if there are only single 'V1', 'V2', per each group, can use diff

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