Ridhima
Ridhima

Reputation: 187

a query regarding plotting piece-wise function in r

I would like to graph the following piece-wise function in R but I am having trouble defining it. I would like to define the following function.It takes the value 0.31 for x between 0 and less than 10 and for x between 10 and 29, it takes the value 0.31-0.00017397(x-10) and similarly for x greater than 29. Below is my R code.

f <- function(x){
ifelse((0 < x & x < 10),0.31,ifelse((10<= x & x < 29),(0.31-0.00017397(x-10)),ifelse((29<=x),(0.31-0.00052702(x-29)),NA)))
}
plot(f,xlim=c(0,35)) 

Many thanks in advance!

Upvotes: 0

Views: 60

Answers (1)

RoyalTS
RoyalTS

Reputation: 10203

This works for me:

f <- function(x){
  ifelse((0 < x & x < 10),0.31,ifelse((10 <= x & x < 29),(0.31-0.00017397*(x-10)),ifelse((29 <= x),(0.31-0.00052702*(x-29)),NA)))
}
plot(f,xlim=c(0,35)) 

(note the * for multiplication)

Upvotes: 1

Related Questions