[R] Do loop
Thomas Lumley
tlumley at u.washington.edu
Tue Apr 22 17:49:30 CEST 2003
On Tue, 22 Apr 2003, N Dey wrote:
> Dear all,
>
> I am doing integration by using integrate(..) command
> of R. Integrand is a function of parameters (say p).
> And I ahve to do the integration for p ranging from 10
> to 500 (eg p<-10*1:50). And I want to store the
> results in a table like.
>
> p result
> 10 ------
> 20 ------
>
> Is there any easy way to do this. I was trying
> for(p<-10*1:50){integrate(Func, lower = 0, upper =
> 182)}, but some problem couldn't do it.
>
>
> > Func<-function(x,p){exp(2*x-(3*p/10))*exp(-(5*x))}
> > for(p in 10*1:50){integrate(Func, lower = 0, upper =
> 182)}
> Error in f(x, ...) : Argument "p" is missing, with no
> default
You need to pass the `p' argument.
One way is
Func<-function(x,p){exp(2*x-(3*p/10))*exp(-(5*x))}
results<-numeric(50)
for(i in 1:50){
result[i]<-integrate(Func,lower=0, upper=182,p=10*i)$value
}
More elegantly
Func<-function(x,p){exp(2*x-(3*p/10))*exp(-(5*x))}
results<-sapply(10*(1:50), function(p) integrate(Func,
lower=0,upper=182,p=p)$value)
-thomas
More information about the R-help
mailing list