[prev in list] [next in list] [prev in thread] [next in thread] 

List:       r-help
Subject:    Re: [R] dependent nested for loops in R
From:       "Berry, Charles" <ccberry () health ! ucsd ! edu>
Date:       2021-01-31 21:26:13
Message-ID: 4937A207-12C7-4877-85D9-1F6DCDDC50B8 () health ! ucsd ! edu
[Download RAW message or body]



> On Jan 30, 2021, at 9:32 PM, Shaami <nzshaam@gmail.com> wrote:
> 
> 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?
> 


Glad to help.

First, it could help you to trace your code.  I suspect that the results are not at \
all what you want and tracing would help you see that.

I suggest running this revision and printing out x, z, and w.

#+begin_src R
  w = NULL
  for(j in 1:2)
  {
    z = NULL
    x = rnorm(10)
    z[1] = x[1]
    for(i in 2:10)
    {
      z[i] = x[i]+5*z[i-1]
      if(z[i]>4 | z[i]<1) {
	w[j]=i
      } else {
	w[j] = 0
      }
    }
  }
#+end_src


You should be able to see that the value of w can easily be obtained outside of the \
`i' loop.

-- 

If inspecting those results did not make you go back and rethink your approach, try \
writing the expression for 

z[n] = x[n] + ... + k * x[1]

If you are not good with algebra write out each of z[1], z[2], z[3] and z[4] in terms \
of x[1:4] and then look at what you have.

Perhaps the value of `k' will surprise you.

In any case, if the code is truly what you intended, you only need x[1:25] to get \
z[n] to double precision for any n.  So, 

Also, you will hardly ever be able to compute the value of z[n] for n > 450. 

If these last two statements are puzzling, see \
https://en.wikipedia.org/wiki/Floating-point_arithmetic

HTH,
Chuck

> 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
> 
> }
> 
> }
> 
> }
> 

______________________________________________
R-help@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.


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic