问题
Here, I would like to have your helps on implementing calculation of integral on two vector. I checked pages on integral calculation relative to R. But, I have few training on mathematics, so I still can not do that by myself.
My objectives is to implement the idea of this sentence "If you plot the rate estimates by position, the genetic map is just the integral of this plot." This mean I have variables (rates, positions), each position have a rate of its own. I want to calculate the integral of rates for each position. Here, the position is Monotonically increasing.
This task should not be so complex for those who have good background on mathematic computation. So, could you please give me any directions/instructions on that?
Thanks in advance.
# here I make dummy data
position <- c(2,34,58)
rate <- c(14, 20, 5)
回答1:
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))
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
来源:https://stackoverflow.com/questions/7358738/how-to-calculate-integral-with-r