[R] dependent nested for loops in R

David Winsemius dw|n@em|u@ @end|ng |rom comc@@t@net
Sun Jan 31 06:01:30 CET 2021


On 1/30/21 8:26 PM, Shaami wrote:
> Hi
> I have very large dependent nested for loops that are quite expensive
> computationally. It takes weeks and does not end to give me results. Could
> anyone please guide how could I use apply function or any other suggestion
> for such big and dependent loops in R? A sample code is as follows.
>
> w = NULL
> for(j in 1:1000)
> {
>    x = rnorm(2000)
>    z = x[1]
>    for(i in 2:2000)
>    {
>      z = x[i]+5*z[i-1]

I'm guessing you meant to type:

         z[i] <- x[i]+5*z[i-1]

>      if(z>4 | z<1) {

And more guesses (in the absence of any sort of problem description) 
that you really wanted:


  if(z[i]>4 | z[i]<1) {  ....


>        w[j]=i
>        break
>      } else {
>        w[j] = 0
>      }
>    }
> }


Are you sure you need a for-loop? Seems like you could have done this 
with a couple of vectorized operations. And the `break` looked entirely 
superfluous.



> Thank you
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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