Skip to content
Prev 387065 / 398502 Next

dependent nested for loops in R

On 1/31/21 1:26 PM, Berry, Charles wrote:
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.