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

syntax for nested ifelse and if statements in R

I am trying to nest if and/or ifelse statements together in R and I can’t quite get the syntax correct. I would like to perform some basic arithmetic: Referencing a similar dataset below, if the date is the same and if the location code is the same, I would like to subtract the pH values of codes A and B from the corresponding pH value for code F and enter the result into pHDelta. Or written out, A – F for a given date and location.

Thank you!

I am not certain the daset that I created below will appear correctly, please pardon me if it does not.

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

My dataset is similar to the following:

Date Location Code pH pHDelta
22/07/01 AA A 7.1
22/07/01 AA B 6.8
22/07/01 AA F 8.2
22/07/01 AB A 7. 2
22/07/01 AB B 7.8
22/07/01 AB F 8.4
22/07/01 AC A 7.5
22/07/01 AC B 6.2
22/07/01 AC F 8.3
22/07/01 AD A 7.1
22/07/01 AD B 6.8
22/07/01 AD F 8.2
22/07/02 AA A 7.1
22/07/02 AA B 6.8
22/07/02 AA F 8.2
22/07/02 AB A 7.2
22/07/02 AB B 7.8
22/07/02 AB F 8.4
22/07/02 AC A 7.5
22/07/02 AC B 6.2
22/07/02 AC F 8.3
22/07/02 AD A 7.1
22/07/02 AD B 6.8
22/07/02 AD F 8.2

>Solution :

We can use a group by approach – grouped by ‘Date’, ‘Location’, subset the ‘pH’ where ‘Code’ value is "F" (assuming only a single "F" per Location) and then subtract from the ‘pH’ column

library(dplyr)
df1 <- df1 %>%
     group_by(Date, Location) %>%
     mutate(phDelta = pH - pH[Code == "F"][1]) %>%
     ungroup
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