mardi 5 janvier 2016

3-section transformation function in R

I hope this question is new as I couldn't find a solution that worked for me.

I have a vector x that can be filled with any real numbers. The elements in this vector should be transformed by a function in the following way:

x = 0, if x < a

x = (x-a)/(b-a), if a <= x <= b

x = 1, if x > b

This is the function I came up with:

transf <- function(x, a = 0, b = 1){
  if(a > b) stop("\nThe lower bound must be smaller than the upper bound!")

  if(x < a){
    y = 0
  }
  else if(a <= x <= b){
    y = (x-a)/(b-a)
  }
  else{
    y = 1
  }
  return(y)
  print(y)
}

I get a bunch of error messages that I can't quite put together. I also tried replacing else if and else with a simple if, but that didn't work either.

Any help on how to solve this would be very much appreciated

Aucun commentaire:

Enregistrer un commentaire