curious_cat curious_cat - 1 year ago 70
R Question

vectorized way to code function in R

If I want to code a math function:

= 12 for x>1
= x^2 otherwise

If I use


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 Source

Would something like this work:

mathfn <- function(x) ifelse(x > 1, 12, x^2)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download