[Solved] how to calculate integral with R


In mathematics, an integral is the area under the curve. In your example, you want the area under the curve as defined by position and rate.

position <- c(2,34,58)
rate <- c(14, 20, 5)  

plot(position, rate, type="l", ylim=c(0, 25))

enter image description here

You can calculate the area under the curve by hand, using the trapezoidal rule:

32*17 + 24*12.5 = 844

Or, to do it programmatically:

AUC <- function(x, y){
  sum(diff(x)*rollmean(y,2))
}

AUC(position, rate)
[1] 844

2

solved how to calculate integral with R