简体   繁体   中英

Define and plot a PieceWise function in R

I have tried to define this function with RStudio but im having a lot of problems and cant understand whats wrong

x <- seq(-10, 10, 0.001)
fx <- function()
if(x < 0 ) {fx<- sin(x)
} 
 else if (x >= 0 && x < 2) 
   {
   fx<- x^2
 } 
  else if(x >= 2 )
    { 
    fx<- 4*exp(x-2)
  }
}
plot(x, fx)

How could i do this? I can't find anything useful on the internet

Your function shouldn't be using if for vectors. Best to us ifelse , or just utilise R's vector capabilities:

fx <- function(x){
    f <- NULL
    f[x<0] <- sin(x[x<0])
    f[x>=0 & x<2] <- x[x>=0 & x<2]^2
    f[x>=2] <- 4*exp(x[x>=2] - 2)
    f
}

x <- seq(-10, 3, 0.01)
plot(x, fx(x), type="l", las=1)

在此处输入图像描述

Try this:

x <- seq(-10, 10, 0.001)

fx <- function(x) {
  if (x < 0) {
    return(sin(x))
  } else if (x >= 0 & x < 2) {
    return(x^2)
  } else {
    return(4*exp(x-2))
  }
}

plot(x, sapply(x, fx))

Created on 2020-04-11 by the reprex package (v0.3.0)

A solution using Vectorize :

x <- seq(-2, 1, 0.001)
f <- function(x) {
  if(x<0) {
    fx <- sin(x)
  } else if (x >= 0 && x < 2) {
    fx <- x^2
  } else if(x >= 2 ) { 
    fx <- 4*exp(x-2)
  }
  fx
}
f <- Vectorize(f)
plot(x, f(x))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM