rnainf

Return NA for division


I am trying to define a new variable that is the division of two other variables.

df$NewVariable <- df$OldVariable1 / (df$OldVariable2/100)

OldVariable2 contains NAs. I'd like NewVariable to return NAs, whenever OldVariable2 is NA. However, when I do summmary(df$NewVariable) after creating it, I get average and maximum of Inf. How can I tell R to produce NAs, so that my new NewVariable isn't affected by any Infs?


Solution

  • Try this:

    df <- data.frame(OldVariable1 = c(2,3,4,4),
                     OldVariable2 = c(3,NA,0,1.5))
    df$NewVariable <- ifelse(df$OldVariable2 == 0, NA, 
                             df$OldVariable1 / (df$OldVariable2/100))
    

    Result:

    > df
      OldVariable1 OldVariable2 NewVariable
    1            2          3.0    66.66667
    2            3           NA          NA
    3            4          0.0          NA
    4            4          1.5   266.66667
    

    Thanks to @Gregor Thomas he pointed out that when you divide a number by NA, or NA/NA you'll get NA, so it wasn't necessary the first condition and you can simplify it.