[R] for loop over dataframe without indices

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Fri Dec 19 09:22:35 CET 2003


Try:

 > data(iris); df<-as.data.frame(t(iris[1:3,]))
 > for(i in df) print(i)
[1] 5.1    3.5    1.4    0.2    setosa
Levels: 0.2 1.4 3.5 5.1 setosa
[1] 4.9    3.0    1.4    0.2    setosa
Levels: 0.2 1.4 3.0 4.9 setosa
[1] 4.7    3.2    1.3    0.2    setosa
Levels: 0.2 1.3 3.2 4.7 setosa

... however, not very nice

Peter Wolf

Gabor Grothendieck wrote:

>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?
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>  
>




More information about the R-help mailing list