Nested if-else loops in R

前端 未结 5 1834
一生所求
一生所求 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 nesting ifelse statements might I recommend using case_when. It is a bit easier to read/follow. But as @Marius mentioned your problem is the && instead of using &.

    library(tidyverse)
    crimes <- data.frame(pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80))
    
    crimes %>% 
      mutate(rate_category = case_when(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))
    

提交回复
热议问题