Skip to content
Back to formatted view

Raw Message

Message-ID: <401E6A2F.8010001@lancaster.ac.uk>
Date: 2004-02-02T15:18:07Z
From: Barry Rowlingson
Subject: for loops?
In-Reply-To: <Pine.OSF.4.30.0402020839560.161133-100000@darwin.epbi.cwru.edu>

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