[R] "factorise" variables in a data.frame

baptiste auguie ba208 at exeter.ac.uk
Fri Apr 3 12:44:16 CEST 2009


Dear list,

I often need to convert several variables from numeric or integer into  
factors (before plotting, for instance), as in the following example,


d <- data.frame(
	x = seq(1, 10),
	y = seq(1, 10),
	z = rnorm(10),
	a = letters[1:10])
	

d2 <-
within(d, {
	x = factor(x)
	y = factor(y)
	 })
	
str(d)
str(d2)


I'd like to write a function factorise() which takes a data.frame and  
a vector of variable names, and returns the original data.frame with  
the desired variables converted to factor,

factorise <- function(d, f)
***ply(d, f, factor) # some apply function

also, perhaps a defactorise() function doing the reverse operation  
with as.numeric.

I played with the plyr package and the base apply family for a while  
but can't find any concise construct.

Best regards,

baptiste



_____________________________

Baptiste Auguié

School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK

Phone: +44 1392 264187

http://newton.ex.ac.uk/research/emag




More information about the R-help mailing list