[R] loop

jim holtman jholtman at gmail.com
Mon Oct 6 00:45:17 CEST 2014


Please don't post in HTML since your code was all messed up.  You did
not mention what problems you were having with your code.  Now a
couple of things to check is to look at what the structure of "r" that
you are trying to add to "sum" (which should have been "Sum" according
to your assignment earlier in the function.).

Browse[1]> str(r)
List of 5
 $ value       : num 0.0548
 $ abs.error   : num 6.08e-16
 $ subdivisions: int 1
 $ message     : chr "OK"
 $ call        : language integrate(f = integrand2, lower = 0, upper = 2)
 - attr(*, "class")= chr "integrate"

shows that "r" is a list and you want "r$value" to do the addition.
So after formatting your code, and making a couple of corrections, is
this what you were expecting to see:

> B<-function(n){
+     Sum<-1
+     for (k in 0:n){
+         BB<-function(k){
+             integrand2<-function(x,a=1.5){
+
(((a+1)*x)^k)*((2-x)^(n))*(exp(-a*x-2))/(factorial(k)*factorial(n))
+             }
+             integrate(integrand2,0,2)
+         }
+         r<-BB(k)
+         print(r)
+         Sum<-Sum+r$value
+     }
+     print(Sum-1)
+ }
> B(3)
0.05479674 with absolute error < 6.1e-16
0.03780519 with absolute error < 4.2e-16
0.02371485 with absolute error < 2.6e-16
0.01355982 with absolute error < 1.5e-16
[1] 0.1298766

Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.


On Sun, Oct 5, 2014 at 6:01 PM, pari hesabi <statistics84 at hotmail.com> wrote:
> Hello ,I am trying to write a loop for sum of integrals .
> the integral is:integrand4<-function(x,a=1.5,n=3,k=0){(((a+1)*x)^k)*((2-x)^n)*(exp(-a*x-2))/(factorial(k)*factorial(n))}
>
> integrate(integrand4,0,2).
> I need a loop to give me the sum of integrals over k = 0,.....n , for every positive integer input (n).can anybody check my program and tell me about it's problem?I am looking forward to your suggestions.
> B<-function(n){Sum<-1for (k in 0:n){BB<-function(k){integrand2<-function(x,a=1.5){(((a+1)*x)^k)*((2-x)^(n))*(exp(-a*x-2))/(factorial(k)*factorial(n))} integrate(integrand2,0,2)}r<-print(BB(k))sum<-sum+r}print(sum-1)}
>
> Best Regards,Diba
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list