Reputation: 39
I would like to find the area under the curve that is produced by running the following code:
L <- 11 #increments
#time vector
t0 <- 0
t1 <- 1
t <- seq(from = t0, to = t1, by = (t1-t0)/(L-1))
#mass flow rate
m <- c(0.00000, 85.44207, 247.48737, 519.72348, 987.59247, 1679.37861, 2629.25871,
3535.53391, 4378.75874, 5020.45815, 5288.56947)
plot(t, m, type = "l", col = "red", lwd = 5)
Upvotes: 1
Views: 85
Reputation: 102529
Probably you can try interpolation first and then integrate
, e.g.,
> fl <- \(x) approxfun(t, m)(x) # linear interpolation
> integrate(fl, 0, 1)$value
[1] 2172.785
or
> fs <- \(x) splinefun(t, m)(x) # spline interpolation
> integrate(fs, 0, 1)$value
[1] 2173.054
If your curve consists of linear segments, you can use the following two simple approaches as well
> # if step size is NOT uniform
> sum(rowSums(embed(m, 2)) * diff(t)) / 2
[1] 2172.792
> # if step size if uniform
> (sum(m) - mean(range(m))) * (t1 - t0) / (L - 1)
[1] 2172.792
To visualize the interpolated curves, you can refer to the following example
plot(t, m, type = "p", lwd = 3)
curve(fl, 0, 1, add = TRUE, col = "blue", lwd = 2)
curve(fs, 0, 1, add = TRUE, col = "red", lwd = 2)
legend(
x = "topleft",
legend = c("data", "approxfun", "splinefun"),
lwd = 2,
col = c("black", "blue", "red"),
text.font = 2
)
grid(10)
Upvotes: 6