Home > Mobile >  Nested IfElse statements in R not returning values as expected
Nested IfElse statements in R not returning values as expected

Time:10-03

I am trying to code the following in R. I think it needs a series of nested ifelse statements. I can get my code to work but it doesn't seem to work properly.

enter image description here

I want to be able to classify a range according to these rules, where values <a = 0, between b and c = 1 and then > a = 0.

enter image description here

This is my code.

   x <- 105     # Just a test value, I substitute numbers to test the code
   a <- 1
   b <- 40
   c <- 60
   d <- 100

    alpha <- if(x <= a){
       (alpha == 0)
    } else if(x >= a & x < b){
      (1-(x - a)/(b - a)) * (pi/2)
    } else if (x >= b & x < c){
      (alpha == 1)
    } else if(x >= c & x < d){
      ((x - c)/(d - c)) * (pi/2)
    } else if(x >= d){
      (alpha == 0)
    }

    newvalue <- if (alpha == 0){
      newvalue == 0
    } else if (alpha == 1){
      newvalue == 1
    } else {
      cos(alpha)^2}

I think there might be something wrong with how I am nesting the statements? I have looked at other examples but I can't see what problem I'm making?

CodePudding user response:

dplyr::case_when makes things much clearer in these cases of multiple nested ifelses:

library(dplyr)

alpha <- case_when(x<a ~ 0,
                  x>=a & x<b ~ (1-(x - a)/(b - a)) * (pi/2)),
                  x>=b & x< c ~ 1,
                  x>=c & x<d ~ ((x - c)/(d - c)) * (pi/2)),
                  x>=d ~ 0)

newvalue <- case_when(alpha==0 ~ 0,
                      alpha==1 ~1,
                      TRUE ~ cos(alpha)^2)
                  

CodePudding user response:

Try,

alpha <- if(x <= a){
  (alpha = 0)
} else if(x >= a & x < b){
  (1-(x - a)/(b - a)) * (pi/2)
} else if (x >= b & x < c){
  (alpha = 1)
} else if(x >= c & x < d){
  ((x - c)/(d - c)) * (pi/2)
} else if(x >= d){
  (alpha = 0)
}

newvalue <- if (is.null(alpha) == 0){
  (newvalue = 0)
} else if (is.null(alpha) == 1){
  (newvalue = 1)
} else {
  cos(alpha)^2}
  • Related