[R] Index of a Loop Variable?

Gabor Grothendieck ggrothendieck at myway.com
Wed Apr 7 06:29:37 CEST 2004


>

You could define the utility function iter:

iter <- function(x) mapply( x, seq(along=x),
                      FUN=function(x,i)list(x=x,i=i), SIMPLIFY=F )

and use it like this to loop over seq(5,50,5) and 1:10 simultaneously:

  > for(idx in iter(seq(5,50,5))) with(idx, cat(x,i,"\n"))
  5 1 
  10 2 
  15 3 
  20 4 
  25 5 
  30 6 
  35 7 
  40 8 
  45 9 
  50 10 



Jim Java writes--

 
 Hi Everyone:--
 
 Is it possible, within a for loop not explicitly using whole-number
 indexing, to find out the index value of the loop variable within the
 vector or list that's being looped through? For example, in --
 
 x <- seq(5, 50, by=5)
 index.in.x <- 1
 for (i in x) {
   cat(paste(" index of i-value ", i, " within x: ", index.in.x, sep=""), 
fill=T)
   index.in.x <- index.in.x + 1
 }
 
  -- is it in general possible to get values of "index.in.x" without
 making it a count variable, as above?
 
 Thank you.
 
  -- Jim Java




More information about the R-help mailing list