2

If I want to code a math function:

f(x)
     = 12 for x>1
     = x^2 otherwise

If I use

mathfn<-function(x)
{
    if(x>1)
    {
        return(12)
    }
    else
    {
        return(x^2)
    }
}

then I suppose that's not a good way to code it because it's not generic for calls in which x is a vector. e.g. plot() or integrate() fail.

plot(mathfn, 0,12)
Warning message:
In if (x > 1) { :
  the condition has length > 1 and only the first element will be used

What's a more robust, vectorized idiom to code this so that x can either be a scalar or a vector?

curious_cat
  • 805
  • 2
  • 9
  • 24

1 Answers1

4

Would something like this work:

mathfn <- function(x) ifelse(x > 1, 12, x^2)
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
User2321
  • 2,952
  • 23
  • 46