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
  • 755
  • 2
  • 7
  • 23

1 Answers1

4

Would something like this work:

mathfn <- function(x) ifelse(x > 1, 12, x^2)
David Arenburg
  • 89,637
  • 17
  • 130
  • 188
User2321
  • 2,610
  • 18
  • 37