Search code examples
rdataframemutate

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:

   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))