How to define piecewise function in R

I want to define a piecewise function using R, however my R code is going 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 }
+5
source share
6 answers

Or you can use ifelse.

fx <- ifelse(x > -0.326 & x <0.625, 0.632,
   ifelse(x > -1.793 & x < -1.304,  0.454,
   ifelse(x > 1.630 & x < 2.119, 0.227, 0)))
+12
source

Try the following:

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)
+15
source

, , . R .

cuts vals :

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 )

findInterval x :

fx <- vals[findInterval(x, c(-Inf, cuts))]

, , vals, , list, .

Alternatively, since this function is stepwise, you can use stepfun:

f <- stepfun(cuts[-1], vals)
fx <- f(x)

Then you can also use good construction methods stepfun.

+10
source

Perhaps if you separate the conditions

if((-1.793<x) & (x < 0.652)) ...

EDIT: That seems to be not all, there is a different approach here:

x<-seq(-5, 5, by=0.01)
fx <- function(x) {
    res <- rep(0, length(x))
    res[(-0.326 < x) & (x < 0.652)] <- 0.632
    res[(-1.793<x) & (x < (-1.304))] <- 0.454  
    res[(1.630<x) & (x <2.119)] <- 0.227  
    return(res)
}
fx(x)
+2
source

Another option, this time using cut.

regions <- c(-Inf, -1.793, -1.304, -0.326, 0.652, 1.63, 2.119, Inf)
group <- cut(x, regions)
f_values <- c(0, 0.454, 0, 0.632, 0, 0.227, 0)
(fx <- f_values[group])
+2
source

If you have different cutoff points, I would use switch. Here is an example with simplified cutout values.

xcuts<-1:10 #the values at which you change fx assignment
xx<- seq(1.5,10,5, by =10) #vector of fx values to be selected
switch(max(which(x>xcuts)), 
1= fx<-xx[1], 
2= fx<-xx[2], 
..."et cetera"... 
) 

Loop over x.

+1
source

All Articles