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

Calculating new column based on multiple conditions in R

I have a data frame with the following sample format:

   ID          Date         Pressure_ft          Pressure_psi
   3           09-09        65                   NA
   4           09-09        NA                   45
   5           09-09        63                   NA

I want to create a new column that convert the values from the Pressure_psi column into the pressure_ft. To do this I just need to divide the psi column by 2.31.

I have used the following code:

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

   df <- mutate(df, calculation = Pressure_psi/2.31)

However this then creates a new column and the old pressure_ft column and the new calculation are separate when I need them to be a singular column.

>Solution :

If your goal is to replace the NA values in Pressure_ft with the calculated values from the Pressure_psi, then you can use a conditional statement to replace the NA’s

df$Pressure_ft <- ifelse(is.na(df$Pressure_ft), df$Pressure_psi/2.31, df$Pressure_ft)

This says set df$Pressure_ft to one of two values:

  • if Pressure_ft is an NA value, then use Pressure_psi/2.31
  • otherwise use the existing Pressure_ft value

You can also use this in the same tidy format:

df%>%
   mutate(Pressure_ft=ifelse(is.na(Pressure_ft), Pressure_psi/2.31, Pressure_ft))
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