[R] loop function and integrate?

Berend Hasselman bhh at xs4all.nl
Fri Nov 30 19:47:28 CET 2012


On 30-11-2012, at 19:34, Berend Hasselman wrote:

> 
> On 30-11-2012, at 16:08, faeriewhisper wrote:
> 
>> Hi guys! 
>> I have to compute something and i don't know what i'm doing wrong. my code
>> is a bit complex, but imagine that is something like this: 
>> 
>> a = c(1,2,3,4) 
>> ia = length(a) 
>> 
>> x = seq(1,100,length=0.1) 
>> ib = length(x) 
>> 
>> int1 = numeric(ib) 
>> b = numeric(ib) 
>> 
>> for(j in 1:ia) { 
>>  H = function(x) {sin(x + a[j])} 
>>     for(i in 1:ib) {	
>>               int =  integrate(H, lower = 0, upper = x[i]) 
>>               int1[i] = int[1] 
>>               b[i] = 1 + a[i] 
>>               } 
>>       end 
>>  int1 = unlist(int1) 
>>  int2 = int1*b 
>>  ss[j] = sum(int2) 
>> } 
>> end 
>> 
> 
> What are you doing?
> What's the "end" doing in your code in two places.
> end is a function to extract and encode the last observation of a time series object. See ?end
> It makes absolutely no sense to put them in your code.
> Remove them immediately.
> 
> You haven't declared ss to be a vector.
> So before the start of the j loop insert ss <- numeric(ia)
> 
> And simplify your code:
> 
> ss <- numeric(ia)
> 
> for(j in 1:ia) { 
>  H = function(x) {sin(x + a[j])} 
>     for(i in 1:ib) {	
>               int =  integrate(H, lower = 0, upper = x[i])  
>               int1[i] = int$value
>               b[i] = 1 + a[i] 
>               }
>  ss[j] = sum(int1*b)    
> } 
> ss
> 
> And more simplification is possible by eliminating b, which I leave to you.

There is no need to define the function H in the j loop.
You could do this:

H = function(x,A) {sin(x + A)}

for(j in 1:ia) {
     aj <- a[j]
     for(i in 1:ib) {
               int =  integrate(H, lower = 0, upper = x[i], A=aj)
               int1[i] = (1 + a[i])* int$value
               }
  ss[j] = sum(int1)
}

And if Rui is right  a[i] can be replaced by aj.

Berend




More information about the R-help mailing list