Nested if-else loops in R

前端 未结 5 1872
一生所求
一生所求 2021-01-19 03:28

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

5条回答
  •  旧时难觅i
    2021-01-19 04:14

    You may use algebraic approach to solve your problem, it should be faster than your ifelse:

    pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80) 
    crimes = data.frame(pre_rate)   
    crimes$rate = (pre_rate > 0.26 & pre_rate < 0.87)*1 + 
      (pre_rate > 1.04 & pre_rate < 1.94)* 2 + 
      (pre_rate > 2.03 & pre_rate < 2.96)* 3 + 
      (pre_rate > 3.10 & pre_rate < 3.82)* 4 + 
      (pre_rate > 4.20 & pre_rate < 11.00)* 5
    

    The idea here is to just get true or false values from expression, then it is getting multiplied by the number for which you see that as a category. The only difference would be that you won't be getting NAs here for non match instead you will get a zero, which you can off course change it. Also to add, Use "&" in cases where you want to vectorize (element by element match) your outcome as mentioned in the comments.

    Output:

    #> crimes
    # pre_rate rate
    #1     0.27    1
    #2     1.91    2
    #3     2.81    3
    #4     3.21    4
    #5     4.80    5
    

提交回复
热议问题