curious_cat - 8 months ago 40

R Question

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?

Source (Stackoverflow)