mutate and ifelse do not work with data contained negative values

Hi friends, i struggle to define new variable, which depends upon mutate and ifelse commands. I try to define risk scale in the below. CN.PROB variable is a decimal variable as -0.20 and it is between -1 to 0.60
When i run this code, it creates just "NON"

a<-chnvar.KAD %>% mutate(Risk_level=ifelse(CN.PROB %in% -1.10:-0.60, "Very Low Risk",
ifelse(CN.PROB %in% -0.59:-0.20, "Low Risk",
ifelse(CN.PROB %in% -0.19:-0.01, "Medium Risk",
ifelse(CN.PROB %in% 0:0.20, "Higher Risk",
ifelse(CN.PROB %in% 0.20:0.60, "Highest Risk", "NON"))))))

Hi oktayozden,

  1. The below code should help you. Try it out and write back if you come across any issues. Simply copy-paste this code to RStudio console and execute
  2. The value 0.20 is repeating in both 'Higher' and 'Highest' risk categories; I have revised it to 0.21 under highest risk. Feel free to modify
  3. In absence of the actual data, i have setup a sample vector with sample values under the name 'chnvar.KAD'
  c(0.20,-0.10,-3.50,-0.60,-1.10,-0.59,-0.20,-0.19,-0.01,0,0.60,0.22,-0.70,-0.48,-2.00) %>%
  data.frame() %>%

a<-chnvar.KAD %>% 
            ifelse(between(CN.PROB,-1.10,-0.60),"Very Low Risk",
            ifelse(between(CN.PROB,-0.59,-0.20),"Low Risk",
            ifelse(between(CN.PROB,-0.19,-0.01),"Medium Risk",
            ifelse(between(CN.PROB,0,0.20),"Higher Risk",
            ifelse(between(CN.PROB,0.21,0.60),"Highest Risk","NON"))))))

Below is how the output of this code looks like:

   CN.PROB    Risk_level
1     0.20   Higher Risk
2    -0.10   Medium Risk
3    -3.50           NON
4    -0.60 Very Low Risk
5    -1.10 Very Low Risk
6    -0.59      Low Risk
7    -0.20      Low Risk
8    -0.19   Medium Risk
9    -0.01   Medium Risk
10    0.00   Higher Risk
11    0.60  Highest Risk
12    0.22  Highest Risk
13   -0.70 Very Low Risk
14   -0.48      Low Risk
15   -2.00           NON

Warm Regards,


Consider using case_when() for such scenarios:


Thanks a lot Pritish. It works!
Last questions is : "between(CN.PROB,-1.10,-0.60),"Ver...", whether, in this "between function", -1.10 and -0.60 are including or not?

Happy to hear that it worked!

Yes, the ends are included. Below is how the between function works:
between(x,a,b) will check for x>=a and x<=b

The line 4 of the sample output that I have posted above confirms this in which -0.60 is the upper limit of the 'Very Low Risk' category.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.