Search code examples
rfunctionpiecewise

How to define a piecewise function in R


I want to define a piecewise function using R, however, my R code goes wrong. Any suggestion is welcome.

x<-seq(-5, 5, by=0.01)
  for (x in -5:5){
  if (-0.326 < x < 0.652) fx<- 0.632
  else if (-1.793<x<-1.304) fx<- 0.454  
  else if (1.630<x<2.119) fx<-0.227  
  else fx<- 0 }

Solution

  • Or you could use ifelse.

    fx <- ifelse(x > -0.326 & x <0.625, 0.632,
       ifelse(x > -1.793 & x < -1.304,  0.454,
       ifelse(x > 1.630 & x < 2.119, 0.227, 0)))