Skip to content

:Problem with Looping

3 messages · Bruno Giovannetti, Benilton Carvalho, Nordlund, Dan (DSHS/RDA)

#
Hello,

Sometimes the looping (using "for") seems to skip some iterations.

An example:

arg <- matrix(NA,length(seq(.30,.5,.01)),1)
for (i in seq(.30,.5,.01)) {
arg[i*100-29] <- i
}
arg

What is the problem with this coding, please?

Thank you so much,
#
it doesn't skip...

think about why:

seq(.30,.5,.01) * 100 - 29 == 1:21

isn't always TRUE.

b
On Nov 17, 2009, at 9:17 PM, Bruno Giovannetti wrote:

            
#
Don't use floating point operations in your indexing.  You may also want to change how you generate your sequence.  This is a floating point representation problem. See FAQ 7.31.  Try something like this

arg <- matrix(NA,length(seq(30,50,1)),1)
for (i in seq(30,50,1)) {arg[i-29] <- i/100 }

Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA  98504-5204