I'm a little late to the party, but I couldn't resist posting a couple more ways to do this. Both take advantage of R capabilities for working with intervals on the real line.
If you define your cut points and function values in the vectors cuts
and vals
like so:
cuts <- c( -Inf, -1.793, -1.304, -0.326, 0.625, 1.630, 2.119 )
vals <- c( 0, 0.454, 0, 0.632, 0, 0.227, 0 )
Then you can use findInterval
to efficiently look up the values of x
in your cutpoints:
fx <- vals[findInterval(x, c(-Inf, cuts))]
If this function needed to do fancier stuff than just look up a constant value, you can put expressions or functions or whatever you want in vals
, possibly using a list
if you want.
Alternatively, since this function is a step function, you can use stepfun
:
f <- stepfun(cuts[-1], vals)
fx <- f(x)
Then you also get to use the nice plotting methods of stepfun
too.
stepfun
(mentioned by @KenWIlliams) andapproxfun
both work well.approxfun
also accommodates piecewise-linear functions (but not general piecewise functions). – Tagmeme