[R] make apply() return a list
Gabor Grothendieck
ggrothendieck at myway.com
Mon Nov 1 19:59:43 CET 2004
Arne Henningsen <ahenningsen <at> email.uni-kiel.de> writes:
:
: Hi,
:
: I have a dataframe (say myData) and want to get a list (say myList) that
: contains a matrix for each row of the dataframe myData. These matrices are
: calculated based on the corresponding row of myData. Using a for()-loop to
do
: this is very slow. Thus, I tried to use apply(). However, afaik apply() does
: only return a list if the matrices have different dimensions, while my
: matrices have all the same dimension. To get a list I could change the
: dimension of one matrix artificially and restore it after apply():
:
: This a (very much) simplified example of what I did:
: > myData <- data.frame( a = c( 1,2,3 ), b = c( 4,5,6 ) )
: > myFunction <- function( values ) {
: + myMatrix <- matrix( values, 2, 2 )
: + if( all( values == myData[ 1, ] ) ) {
: + myMatrix <- cbind( myMatrix, rep( 0, 2 ) )
: + }
: + return( myMatrix )
: + }
: > myList <- apply( myData, 1, myFunction )
: > myList[[ 1 ]] <- myList[[ 1 ]][ 1:2, 1:2 ]
Try lapplying over the columns of the transpose:
lapply(as.data.frame(t(myData)), matrix, 2, 2)
More information about the R-help
mailing list