dimanche 3 décembre 2017

Nested if-else loops in R

I have a data frame named "crimes" which contains a "pre_rate" column that denotes the crime rate before a certain law is implemented. I would like to put each rate in a "rate_category" column using a nested if-else loop. I have the following code:

crimes$rate_category = 
  with(crimes, ifelse(pre_rate > 0.26 && pre_rate < 0.87, 1,
    ifelse(pre_rate > 1.04 && pre_rate < 1.94, 2, 
      ifelse(pre_rate > 2.03 && pre_rate < 2.96, 3, 
        ifelse(pre_rate > 3.10 && pre_rate < 3.82, 4, 
          ifelse(pre_rate > 4.20 && pre_rate < 11.00, 5, "NA"))))))
crimes

and here's a reproducible example:

pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80) 
crimes = data.frame(pre_rate)   
crimes

However, when I run the loop with my original data frame, all levels in the "rate_category" column is incorrectly set to 1. What seems to be the problem with the loop above?

Aucun commentaire:

Enregistrer un commentaire