[R] For loop indicies

Sarah Goslee sarah.goslee at gmail.com
Mon Dec 12 12:53:18 CET 2011


On Mon, Dec 12, 2011 at 6:44 AM, Thomas Chesney
<Thomas.Chesney at nottingham.ac.uk> wrote:
> I would like to run a for loop with an index going from 0 to 499 but the following seems to miss out the first value:
> C <- 499
> for (i in 0:C)

First off, you've named your variable for an existing function, which
can cause all kinds of problems.

Second, this should work just fine, as it does for me:

> maxvar <- 4
> for(i in 0:maxvar) cat(i, "\n")

What leads you to think that it's not working?

> The alternative is:
> C <- 500
> for (i in 1:C)
> {
> #Then every time I use i, I replace it with i-1
> }
> Is this a good way to do it or is tere a better way?

There's a better way to ask your question, at least: give us
reproducible code, and explain what you are not seeing that you expect
to see, or vice versa. "seems to miss out on the first value" - what
happens? If I can't reproduce it, I can't help you solve it.

Sarah Goslee

More information about the R-help mailing list