Defining a piecewise function with if and else statements in Rstudio

Viewed 88

Disclaimer as I am extremly new. I am trying to make a piecewise function but I get the error that a symbol is wrong? What am I doing wrong. Help is much appreciated!

g<-function(x){if ( x < 0) {
  0
  } else if ( x <= 1) {
  x^2
  } else if ( x >= 0) {
  x^2
  } else {
  2x-1
  }
}
1 Answers

As G. Grothendieck pointed out in the comment, you missed * in 2*x-1


Below are two variants for your piece-wise function

g1 <- function(x) pmax(ifelse(x > 1, 2 * x - 1, sign(x) * x^2), 0)
g2 <- function(x) ifelse(x > 1, 2 * x - 1, ifelse(x < 0, 0, x^2))
Related