[R] loop function and integrate?

Rui Barradas ruipbarradas at sapo.pt
Fri Nov 30 19:28:37 CET 2012


Hello,

Your code doesn't run without initializing 'ss' to something. And I've 
made some changes, but I don't understand what you are trying to do. See 
comments inline.


a = c(1,2,3,4)
ia = length(a)

x = seq(1, 100, by=0.1)   # It was 'length = 0.1' (!)
ib = length(x)

ss <- numeric(ia)  # New, 'ss' must exist.
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[j]   # It was 'a[i]', didn't make any sense.
     }
     int1 = unlist(int1)
     int2 = int1*b
     ss[j] = sum(int2)
}
ss


And for loops (or any other type of loops) do _not_ end with 'end'.

Hope this helps,

Rui Barradas

Em 30-11-2012 15:08, faeriewhisper escreveu:
> 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
>
> if i try this code without the for loop it's ok, but when i put the for on,
> i get all sort of errors...
> Thank you for your help :)
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/loop-function-and-integrate-tp4651436.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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