[R] for loops?

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Mon Feb 2 16:18:07 CET 2004


Catherine Stein wrote:

> How can one use a for loop (or something similar) in R?  As I type in each
> line, I get syntax errors... I'm just confused how much to type in at each
> ">" prompt.
> 

  Have you read help("for") (you need to quote 'for' here to avoid a 
syntax error!)?

  If you'd shown us exactly what you'd typed we could probably help 
better. Suppose you want to loop from 1 to 10 and print it. You can do 
the following, where '>' is the R prompt (dont type it):

  > for(i in 1:10)print(i)
     - ie all on one line

  > for(i in 1:10){print(i)}
     - with curly brackets

  > for(i in 1:10)
  + print(i)

    - where '+' is the continuation prompt (dont type it) - R gives you 
this when it realises you havent written a complete expression yet.

  > for(i in 1:10) {
  + print(i)
  + }

     - curly brackets enclose as many expressions as you like inside the 
loop.

  > for(i in 1:10)
  + { print(i)
  + }

     - curly brackets anywhere. R works it out.

  You can even do, and I didn't think this would work...

  > for(i in
  + 1:10)
  + {print(i)}


  So in short, I cant get it to give a syntax error :) What are you 
doing? What version of R, and what platform?

Baz




More information about the R-help mailing list