简体   繁体   中英

R: piecewise functions & plotting

I am trying to make a composite function consisting of 3 exponential functions:

rm(list=ls())
library(mosaic)
library(ggplot2)

# 3 functions
NVent=makeFun(161*exp(-x/51028)~x) # from x [0;259200[
Vent3_4=makeFun(1262*exp(-x/48398)~x) # from x [0;345600[
SVent=makeFun(118*exp(-x/217427)~x) # from x [0;1036800]

#composite function
QTOT <- function(x) {
  if (x<259200) return(NVent(x)+Vent3_4(x)+SVent(x)),
  if (259200<x<345600) return(Vent3_4(x) + SVent(x)),
  if (345600<x<1036800) return(SVent(x))
} 

but get an error:

Error: unexpected '<' in:
"  if (x<3) return(NVent(x)+Vent3_4(x)+SVent(x))
  if (3<x<"
>   if (4<x<12) return(SVent(x))
Error: unexpected '<' in "  if (4<x<"
> }
Error: unexpected '}' in "}"
> 

As far as understand I don´t write the intervals correctly, but have not been able to correct it nor find examples that can help me, so I would really appreciate your input !

您的条件应为:

259200<x && x<345600

So for future users I just wanted to post what I eventually found to be the best way to write this piecewise function:

NVent=makeFun(161*exp(-x/51028)~x)
Vent3_4=makeFun(1262*exp(-x/48398)~x) 
SVent=makeFun(118*exp(-x/217427)~x) 

f1=makeFun(NVent(x)+Vent3_4(x)+SVent(x)~x)
T1 <- 3*24*3600
f2=makeFun(Vent3_4(x)+SVent(x)~x)
T2 <- 4*24*3600
f3=makeFun(SVent(x)~x)
T3 <-12*24*3600

#Piecewise function
QTOT <- function(x) 
  (x > 0 & x <= T1)*f1(x) + (x > T1 & x < T2)*f2(x) + (x > T2 & x <T3)*f3(x)

# Plot of piecewise function
curve(QTOT, xlim = c(0,T3))  

This allowed me to plot the piecewise function using curve or matplot, while I in the previous code had the problem that only the first part of the piecewise function was plotted.

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