# Load packages library(deSolve) library(ggplot2) # Define parameters init_volume <- 100 # Initial volume of tank in litres outflow <- c(1,1,2,1,2,2,1,1,1,2) # Outflow (litres/hour) for each hour times <- seq(0, 9, by = 1) # Simulation time in hours # Define tank model function tank_model <- function(time, volume, parameters) { dV <- -parameters["outflow"][time+1] # Change in volume is equal to the outflow rate return(list(dV)) } # Set up initial conditions and run simulation init_state <- c(V = init_volume) # Initial state of the tank parameters <- list(outflow = outflow) # Parameters for the simulation out <- ode(y = init_state, times = times, func = tank_model, parms = parameters) # Plot tank volume over time and save as PDF file pdf("tank_volume_plot.pdf") # Specify PDF file name ggplot(data = data.frame(time = out[,1], volume = out[,2])) + geom_line(aes(x = time, y = volume)) + labs(title = "Tank Volume Over Time", x = "Time (hours)", y = "Volume (litres)") dev.off() # Close PDF device