Nested if-else loops in R

前端 未结 5 1873
一生所求
一生所求 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:17

    Instead of multiple nested ifelse(), a non-equi join and update on join can be used

    # OP's sample data set with one out-of-bounds value appended
    crimes = data.frame(pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80, 1.0))   
    
    library(data.table)
    # specify categories, lower, and upper bounds
    bounds <- data.table(
      cat = 1:5,
      lower = c(0.26, 1.04, 2.03, 3.10, 4.2),
      upper = c(0.87, 1.94, 2.96, 3.82, 11)
    )
    # non-equi join and update on join
    setDT(crimes)[bounds, on = .(pre_rate > lower, pre_rate < upper), rate_category := cat][]
    
       pre_rate rate_category
    1:     0.27             1
    2:     1.91             2
    3:     2.81             3
    4:     3.21             4
    5:     4.80             5
    6:     1.00            NA
    

    Note that pre-rate values which are outside of any of the given intervals do get a NA rate_category automatically.

提交回复
热议问题