Search code examples
rsubtractionmutate

Subtracting a column value which corresponds to a specific value in another column from the every row in that column in R


Fish_ID Instance Success First_Success Inst_Diff
1 0 0 0 -2
1 1 0 0 -1
1 2 1 1 0
1 3 0 0 1
1 4 1 0 2
1 5 0 0 3
results %>%
  group_by(Fish_ID) %>%
  mutate(Inst_Diff = Instance- Instance[First_Success==1])

I want to create a Inst_Diff column. Using instance number where the first success equals to 1 then the ‘Inst_Diff’ is equivalent to: (Instance) - (Instance at at first success). I have more than one Fish_ID. I tried to code above but it gives an error. I would appericate your suggestions. Thank you!


Solution

  • An approach using first

    library(dplyr)
    
    df %>% 
      mutate(Inst_Diff = Instance - first(Instance[Success == 1]), .by = Fish_ID)
      Fish_ID Instance Success First_Success Inst_Diff
    1       1        0       0             0        -2
    2       1        1       0             0        -1
    3       1        2       1             1         0
    4       1        3       0             0         1
    5       1        4       1             0         2
    6       1        5       0             0         3