R 中的嵌套 IfElse 语句未按预期返回值

Nested IfElse statements in R not returning values as expected

我正在尝试在 R 中编写以下代码。我认为它需要一系列嵌套的 ifelse 语句。我可以让我的代码工作,但它似乎无法正常工作。

我希望能够根据这些规则对范围进行分类,其中值 a = 0。

这是我的代码。

   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}

我认为我嵌套语句的方式可能有问题?我查看了其他示例,但看不出我在制造什么问题?

dplyr::case_when 使这些情况下的多个嵌套 ifels 变得更加清晰:

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)
                  

试试,

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}