# [R] dependent nested for loops in R

David Winsemius dw|n@em|u@ @end|ng |rom comc@@t@net
Tue Feb 2 06:19:29 CET 2021

```IMTS length 2000

Sent from my iPhone

> On Feb 1, 2021, at 9:16 PM, David Winsemius <dwinsemius using comcast.net> wrote:
>
> ﻿Cc’ed the list as should always be your practice.
>
> Here’s one way (untested):
>
> W <- +(z>4| z<2) # assume z is of length 20
>
> —
> David
>
> Sent from my iPhone
>
>>> On Feb 1, 2021, at 7:08 PM, Shaami <nzshaam using gmail.com> wrote:
>>>
>> ﻿
>> Hi Prof. David
>>
>> In the following state
>>
>> W = (1:2000)[z >4|z<2)
>>
>> Could you please guide how  I can assign zero if condition is not satisfied?
>>
>> Best Regards
>>
>> Shaami
>>
>>> On Mon, 1 Feb 2021, 11:01 am David Winsemius, <dwinsemius using comcast.net> wrote:
>>>
>>> On 1/31/21 1:26 PM, Berry, Charles wrote:
>>> >
>>> >> On Jan 30, 2021, at 9:32 PM, Shaami <nzshaam using 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?
>>> >>
>>>
>>> I agree with Charles that I suspect your results are not what you
>>> expect. You should try using cat or print to output intermediate results
>>> to the console. I would suggest you limit your examination to a more
>>> manageable length, say the first 10 results while you are working out
>>> your logic. After you have the logic debugged, you can move on to long
>>> sequences.
>>>
>>>
>>> This is my suggestion for a more compact solution (at least for the
>>> inner loop calculation):
>>>
>>> set.seed(123)
>>>
>>> x <- rnorm(2000)
>>>
>>> z <- Reduce( function(x,y) { sum(y+5*x) }, x, accumulate=TRUE)
>>>
>>> w<- numeric(2000)
>>>
>>> w <-  (1:2000)[ z >4 | z < 1 ]  # In your version the w values get
>>> overwritten and end up all being 2000
>>>
>>>
>>> I would also advise making a natural language statement of the problem
>>> and goals. I'm thinking that you may be missing certain aspects of the
>>> underying problem.
>>>
>>> --
>>>
>>> David.
>>>
>>> >
>>> >
>>> > 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.
>>> >

[[alternative HTML version deleted]]

```