如何在R中的for循环中使用sum函数?

Fab*_*olz 1 for-loop r sum integral

在此输入图像描述

我们想要计算线性图中积分的值.为了更好地理解照片.假设总面积为1.我们想要找出某个部分的值是什么.例如,我们想要知道,如果一切都是指月份,那么总体100%中有多少%位于第10个月和第11个月内,而A最大值是24个.我们可以计算积分然后应该能够通过以下方式获得搜索区域: F(x) - F(x-1)我对以下代码感兴趣:

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")
Run Code Online (Sandbox Code Playgroud)

如果你看到情节 - 这很令人困惑.任何想法如何处理这个正确吗?

And*_*rie 5

基本R函数integrate()可以为您执行此操作:

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
Run Code Online (Sandbox Code Playgroud)