[R] conversion of a list of matrices into a dataframe

Wolfram Fischer wolfram at fischer-zim.ch
Thu Jan 23 10:24:03 CET 2003


DATA
	I have data from two (or more) locations with ID: 'A' and 'B'
    for three (or more) YEARS: 1999 to 2001
    of two (or more) variables: VAR1, VAR2.

	> x
	  ID YEAR VAR1 VAR2
	1  A 1999    9    2
	2  B 1999    8    9
	3  A 2000    2    3
	4  B 2000    3    4
	5  A 2001    9    5
	6  B 2001    7    2

DESIRED RESULT
	I want to calculate the rank of the values of each variable
    for each location (ID) in every year.
    I want to get the ranks in a dataframe 'x.ranked'
    having the same structure as the original dataframe 'x'
    (which should be ready for the use by lattice functions).
    
	> x.ranked
	  ID YEAR VAR1 VAR2
	1  A 1999    2    1
	2  B 1999    1    2
	3  A 2000    1    1
	4  B 2000    2    2
	5  A 2001    2    2
	6  B 2001    1    1


EXAMPLE CODE
    x <- data.frame(
          ID    = rep( c('A', 'B' ), 3 )
        , YEAR  = rep( c( 1999, 2000, 2001 ), each=2 )
        , VAR1  = c( 9, 8,  2, 3,  9, 7 )
        , VAR2  = c( 2, 9,  3, 4,  5, 2 )
        )
    vars <- c( 'VAR1', 'VAR2' )

    fun <- function( x, group=NULL ){
        if( ! is.null(group) )      by( x, group, fun )
        else if( ! is.vector(x) )   sapply( x, fun )
        else                        rank( x )
    }

    x.ranked <- fun( x[,vars], x$YEAR )


OBTAINED RESULT
	I got the right values by using the function 'fun',
    but the result does not have the desired structure.
	Can anyone help me to get the desired structure?

	> x.ranked
	group: 1999
		 VAR1 VAR2
	[1,]    2    1
	[2,]    1    2
	--------------
	group: 2000
		 VAR1 VAR2
	[1,]    1    1
	[2,]    2    2
	--------------
	group: 2001
		 VAR1 VAR2
	[1,]    2    2
	[2,]    1    1


Wolfram




More information about the R-help mailing list