[R] for loop over dataframe without indices

Gabor Grothendieck ggrothendieck at myway.com
Fri Dec 19 05:48:34 CET 2003



Based on an off list email conversation, I had I am concerned that
my original email was not sufficiently clear.

Recall that I wanted to use a for loop to iterate over the rows of 
a dataframe without using indices.   Its easy to do this over
the columns (for(v in df) ...) but not for rows.

What I wanted to do is might be something like this. 
Define a function, rows, which takes a dataframe, df, as input 
and converts it to the structure: 
list(df[1,], df[2,], ..., df[n,]) where there are n rows:

     rows <- function( df ) { 
          ll <- NULL
          for( i in 1:nrow(df) ) 
               ll <- append( ll, list(df[i,]) )
          ll 
     }

This allows us to iterate over the rows of df without indices like this:

     data( iris )
     df <- iris[1:3,] # use 1st 3 rows of iris data set as df
     for( v in rows(df) ) print(v)

Of course, this involves iterating over the rows of df twice --
once within rows() and once in the for loop. Perhaps this is
the price one must pay for being able to eliminate index 
computations from a for loop or is it? Have I answered my 
own question or is there a better way to use a for loop 
over the rows of a dataframe without indices?

--- 
Date: Thu, 18 Dec 2003 19:20:04 -0500 
From: Gabor Grothendieck <ggrothendieck at myway.com>
To: <R-help at stat.math.ethz.ch> 
Subject: for loop over dataframe without indices 




One can perform a for loop without indices over the columns
of a dataframe like this:

for( v in df ) ... some statements involving v ...

Is there some way to do this for rows other than using indices:

for( i in 1:nrow(df) ) ... some statements involving df[i,] ...

If the dataframe had only numeric entries I could transpose it
and then do it over columns but what about the general case?




More information about the R-help mailing list