Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate Riemann Sums in R?

Tags:

r

curve

Can any one help how to find approximate area under the curve using Riemann Sums in R?

It seems we do not have any package in R which could help.

Sample data:

MNo1    X1  Y1    MNo2  X2  Y2
1   2981    -66287  1   595 -47797
1   2981    -66287  1   595 -47797
2   2973    -66087  2   541 -47597
2   2973    -66087  2   541 -47597
3   2963    -65887  3   485 -47397
3   2963    -65887  3   485 -47397
4   2952    -65687  4   430 -47197
4   2952    -65687  4   430 -47197
5   2942    -65486  5   375 -46998
5   2942    -65486  5   375 -46998
6   2935    -65286  6   322 -46798
6   2935    -65286  6   322 -46798
7   2932    -65086  7   270 -46598
7   2932    -65086  7   270 -46598
8   2936    -64886  8   222 -46398
8   2936    -64886  8   222 -46398
9   2948    -64685  9   176 -46198
9   2948    -64685  9   176 -46198
10  2968    -64485  10  135 -45999
10  2968    -64485  10  135 -45999
11  2998    -64284  11  97  -45799
11  2998    -64284  11  97  -45799
12  3035    -64084  12  65  -45599
12  3035    -64084  12  65  -45599
13  3077    -63883  13  37  -45399
13  3077    -63883  13  37  -45399
14  3122    -63683  14  14  -45199
14  3122    -63683  14  14  -45199
15  3168    -63482  15  -5  -44999
15  3168    -63482  15  -5  -44999
16  3212    -63282  16  -20 -44799
16  3212    -63282  16  -20 -44799
17  3250    -63081  17  -31 -44599
17  3250    -63081  17  -31 -44599
18  3280    -62881  18  -38 -44399
18  3280    -62881  18  -38 -44399
19  3301    -62680  19  -43 -44199
19  3301    -62680  19  -43 -44199
20  3313    -62480  20  -45 -43999
like image 751
Manoj Kumar Avatar asked Mar 10 '23 21:03

Manoj Kumar


1 Answers

Check this demo :

> library(zoo)
> x <- 1:10
> y <- -x^2
> Result <- sum(diff(x[x]) * rollmean(y[x], 2))

> Result
[1] -334.5

After check this question, I found function trapz() from package pracma be more efficient:

> library(pracma)
> Result.2 <- trapz(x, y)
> Result.2
[1] -334.5
like image 56
xtluo Avatar answered Mar 13 '23 13:03

xtluo