[R] dependent nested for loops in R
    Shaami 
    nz@h@@m @end|ng |rom gm@||@com
       
    Sun Jan 31 06:32:02 CET 2021
    
    
  
Hi
I have made the sample code again. Could you please guide how to use
vectorization for variables whose next value depends on the previous one?
w = NULL
for(j in 1:1000)
{
  z = NULL
  x = rnorm(2000)
  z[1] = x[1]
  for(i in 2:2000)
  {
    z[i] = x[i]+5*z[i-1]
    if(z[i]>4 | z[i]<1) {
      w[j]=i
    } else {
      w[j] = 0
    }
  }
}
On Sun, Jan 31, 2021 at 10:01 AM David Winsemius <dwinsemius using comcast.net>
wrote:
>
> 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.
>
	[[alternative HTML version deleted]]
    
    
More information about the R-help
mailing list