Search code examples
rfor-loopsumintegral

How to use the sum function in a for loop in R?


enter image description here

We want to calculate the value of an integral in linear plot. For a better understanding look at the photo. Let's say the overall area is 1. We want to find what the value in a certain part is. For instance we want to know how much % of the overall 100% lay within the 10th and 11th month if everything refers to months and A as maximum stands for 24. We can calculate a integral and then should be able to get the searched area by F(x) - F(x-1) I thoght about the following code:

a <- 24
tab <-matrix(0,a,1)
tab <-cbind(seq(1,a),tab)
tab<-data.frame(tab)

#initialization for first point
tab[1,2] <- (2*tab[1,1] / a - tab[1,1]^2 / a^2)

#for loop for calculation of integral of each point - integral until to the area
for(i in 2:nrow(tab))
{tab[i,2] <- (2*tab[i,1] / a - tab[i,1]^2/ a^2) - sum(tab[1,2]:tab[i-1,2])}
#plotting
plot(tab[,2], type="l")

If you see the plot - it's confusing. Any ideas how to handle this correct?


Solution

  • The base R function integrate() can do this for you:

    f <- function(x, A) 2/A - x / A^2
    
    integrate(function(x)f(x, 24), lower=10, upper=11)
    
    0.06510417 with absolute error < 7.2e-16