[R] for loop

Michael Bedward michael.bedward at gmail.com
Sat Sep 11 14:29:25 CEST 2010


I've been caught out by this more times than I care to admit -
forgetting that an R for loop isn't a C for loop.

Here's one solution...

k <- start.value
while (k <= end.value) {
  # do stuff
  k <- k + 1
}

Michael

On 11 September 2010 18:39, Yuan Jian <jayuan2008 at yahoo.com> wrote:
> Hello,
> I have a simple question: I want to list numbers 1:k, but if k <1, I hope nothing listed.
> how should we do?
> k=2
> for (i in 1:k)  print(i)
> [1] 1    # <-correct
> [1] 2
> k=0
> for (i in 1:k) print(i)
> [1] 1      #<---- wrong
> [1] 0
>
>
>
> thanks
> jian
>
>
>
>
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
>



More information about the R-help mailing list