Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a piecewise function in R

I want to define a piecewise function using R, however, my R code goes wrong. Any suggestion is welcome.

x<-seq(-5, 5, by=0.01)
  for (x in -5:5){
  if (-0.326 < x < 0.652) fx<- 0.632
  else if (-1.793<x<-1.304) fx<- 0.454  
  else if (1.630<x<2.119) fx<-0.227  
  else fx<- 0 }
like image 320
Frank Wang Avatar asked Jan 09 '12 11:01

Frank Wang


People also ask

How do you define a piecewise function?

A piecewise function is a function built from pieces of different functions over different intervals. For example, we can make a piecewise function f(x) where f(x) = -9 when -9 < x ≤ -5, f(x) = 6 when -5 < x ≤ -1, and f(x) = -7 when -1 <x ≤ 9.


2 Answers

Try this:

x <- seq(-5, 5, 0.01)
fx <- (x > -0.326 & x <0.625) * 0.632 +
      (x > -1.793 & x < -1.304) * 0.454 +
      (x > 1.630 & x < 2.119) * 0.227
plot(x, fx)
like image 127
G. Grothendieck Avatar answered Oct 04 '22 03:10

G. Grothendieck


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.

like image 24
Ken Williams Avatar answered Oct 04 '22 05:10

Ken Williams