Nested if-else loops in R

前端 未结 5 1835
一生所求
一生所求 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条回答
  •  走了就别回头了
    2021-01-19 04:35

    Why not define your lower bounds and upper bounds in two vectors then rely on indexing? Using this method, there is no need to write pre_rate > num1 & pre_rate < num2 multiple times.

    lowB <- c(0.26, 1.04, 2.03, 3.10, 4.2)
    uppB <- c(0.87, 1.94, 2.96, 3.82, 11)
    
    myCategory <- 1:5 ## this can be whatever categories you'd like
    
    crimes$rate_category <- with(crimes, myCategory[pre_rate > lowB & pre_rate < uppB])
    

提交回复
热议问题