[R] Index of a Loop Variable?

Thomas Lumley tlumley at u.washington.edu
Tue Apr 6 16:58:17 CEST 2004


On Tue, 6 Apr 2004, Jim Java wrote:

> 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?

No.

Sometimes it is possible to avoid the need to do this by replacing the
loop with sapply().

Otherwise you probably should use  for(i in seq(length=length(x)) )
and get the elements of x as x[i].

	-thomas




More information about the R-help mailing list