Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading