[R] really dumb question | loop counters in

Greg Snow Greg.Snow at intermountainmail.org
Fri Sep 21 18:24:23 CEST 2007


Try:

for(x in seq(0,1,by=0.01)) {
print(x)
}

The for loop in S/R is what some languages call a foreach loop, you need
to provide a vector of the values to loop over.

If you really want a C style for loop, then just realize that the for
loop is a shorthand while loop:

x <- 0
while( x < 1 ) {
  print(x)
  x <- x + 0.01
}

Hope this helps,


-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at intermountainmail.org
(801) 408-8111
 
 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Evan Cooch
> Sent: Friday, September 21, 2007 10:00 AM
> To: r-help at r-project.org
> Subject: [R] really dumb question | loop counters in 
> 
> Basically new to [R] - as a programming environment at least 
> (had lots of recent experience compiling it on our 
> Opteron-based servers). Was trying to write some simple 
> little scripts (in advance of porting over some bigger things 
> from other environments - like MATLAB), when I realized that 
> handling counters in loop constructs in [R] is not patently 
> obvious (at least, IMO, compared to other languages).
> 
> Suppose I want to iterate something from 1 to 100, using a 
> step size of
> (say) 5. Trying the obvious
> 
> for(x in 1:5:100) {
> print(x)
> }
> 
> (Perhaps obviously, I've borrowed the MATLAB convention to 
> some degree).
> 
> Or, looping from 0 -> 1 by 0.01?
> 
> I've dug through what [R] documentation I have, and all I can 
> find is the somewhat obtuse.
> 
> For example, I can use
> 
> x <- seq(0,1, by=.01)
> 
> But not
> 
> for(x in (0,1,by=0.01)) {
> print(x)
> }
> 
> What about things that are slickly handled in C++, like
> 
> for (node=start; value<threshold && node!=end; 
> node=node->next) { ... }
> 
> 
> OK - I'm stumped (and happy to humiliate myself with what has 
> surely got to be trivial).  I'm happy with a simple basic 
> counter at this point.
> 
> ______________________________________________
> 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