[R] apply, lapply and data.frame in R 2.5

jiho jo.irisson at gmail.com
Mon Jul 30 10:17:53 CEST 2007


Hello everyone,

A recent (in 2.5 I suspect) change in R is giving me trouble. I want  
to apply a function (tolower) to all the columns of a data.frame and  
get a data.frame in return.
Currently, on a data.frame, both apply (for arrays) and lapply (for  
lists) work, but each returns its native class (resp. matrix and list):

apply(mydat,2,tolower) 	# gives a matrix
lapply(mydat,tolower)	# gives a list
and
sapply(mydat,tolower)	# gives a matrix

If I remember well, apply did not used to work on data.frames and  
lapply returned a data.frame when it was provided with one, with the  
same properties (columns classes etc). At least this is what my code  
written with R 2.4.* suggests.

The solution would be:
as.data.frame(apply(mydat,2,tolower))
or
as.data.frame(lapply(mydat,tolower))

But this does not keep columns attributes (all columns are  
reinterpreted, for example strings are converted to factors etc). For  
my particular use stringsAsFactors=FALSE does what I need, but I am  
wondering wether there is a more general solution to apply a function  
on all elements of a data.frame and get a similar data.frame in  
return. Indeed data.frames are probably the most common object in R  
and applying a function to each of its columns/variables appears to  
me as something one would want to do quite often.

Thank you in advance.

JiHO
---
http://jo.irisson.free.fr/



More information about the R-help mailing list