[R] Apply as.factor (or as.numeric etc) to multiple columns

Bengoechea Bartolomé Enrique (SIES 73) enrique.bengoechea at credit-suisse.com
Thu Jun 25 13:57:26 CEST 2009


Very good points  :-)

> - colClasses() in R.utils is similar, except for the particular codes and classes supported, to expandClasses() here.

In fact I saw colClasses() once and got the idea from it, but when I needed the functionallity I did not remember where had I seen it and rewrote it. Now with your hint I can reuse colClasses() instead.  I also use a similar function to facilitate writting long logical vectors: expandLogical("TFTFNFFFTN")

So, with your suggestions:

> x <- data.frame(X="2008-01-01", Y=1.1:3.1, Z=letters[1:3]) 
> data.frame(mapply(function(x, class) match.fun(paste("as", class, sep="."))(x), x, colClasses("Dif"), SIMPLIFY=FALSE), stringsAsFactors=FALSE)

Enrique

-----Original Message-----
From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
Sent: jueves, 25 de junio de 2009 13:41
To: Bengoechea Bartolomé Enrique (SIES 73)
Cc: r-help at r-project.org; mtb954 at gmail.com
Subject: Re: [R] Apply as.factor (or as.numeric etc) to multiple columns

That's quite nice.   Three comments:

- colClasses() in R.utils is similar, except for the particular codes and classes supported, to expandClasses() here.

- not sure if this is important but if as() were the last possibility tried rather than the first then in most cases (in fact all cases handled by expandClasses() ) there would be no use of the methods package.

- paste("as", ...) handles all the common cases including all cases handled by expandClasses() except NA_character_ and could be used as a poor man's doCoerce().




More information about the R-help mailing list