curious_cat curious_cat - 1 month ago 5
R Question

vectorized way to code function in R

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?

Answer

Would something like this work:

mathfn <- function(x) ifelse(x > 1, 12, x^2)
Comments