This is for a function to calculate the AUC using the Midpoint Rule. Using R how can I define a vector that contains the midpoints between values of a previous vector? Or how can I shift the values of a vector to their midpoints?
# define h (or delta x)
h <- (b - a) / n
# define vector based on the limits of integration, a to b by increments of h
xj <- seq.int(a, b, length.out = n + 1
# shift values of vector to their midpoints
For example, to shift the values [0, 1, 2, 3] to become [.25, 1.5, 2.5]
This for loop works but I am wondering if there is a more elegant solution than this:
for (i in 1:length(xj)) {
xji[i] <- (xj[i] + xj[i + 1]) / 2
}
We can use a rolling mean
library(zoo)
rollmean(v1, 2)
#[1] 0.5 1.5 2.5
v1 <- 0:3
For the sake of providing a base R answer, one can use the approx
function which will linearly interpolate (by default) a specified number of points.
v <- c(0,1,2,3)
z <- approx(v, n = length(v)*2 - 1)$y
z
# [1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0
z[-which(z %in% v)]
# [1] 0.5 1.5 2.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With