[R] change the class of an object within with()

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Jun 27 12:31:10 CEST 2006

François MICHONNEAU <francois.michonneau at gmail.com> writes:

> Hello,
> Can anyone explain me what is wrong in the following code? and in particular why it is not 
> possible to change the class of an object thanks to the function with(). Does an 
> alternative exist?
> xxx <- data.frame(x = c("a","b","c","d","e"), y = c("1","2","3","4","5"))
> str(xxx)
> with(xxx, {
> 	x <- as.character(x)
> 	y <- as.numeric(y)
> })
> str(xxx) #no effect on the class of x and y
> xxx$x <- as.character(xxx$x)
> xxx$y <- as.numeric(xxx$y)
> str(xxx)

This is due to the way with() (and eval() & friends) deals with data
frames. The problem is that they are converted internally to
environments before the expressions are evaluated. This means
effectively that any assignments or modifications go into a temporary
copy of the data frame and are then lost. 

This is a bit unfortunate, in that it would be really nice for people
to be able to say 

  with(foo, bmi <- weight/height^2)

and have foo extended with a new bmi column. However, there are snags.
In particular, how would you deal with a computation that yielded a
result that was incompatible with the data frame, like a function, an
lm object, or just a vector of the wrong length? Some of us tend to
think that this should be sorted out eventually, but for now it just
doesn't work. 

You've already shown one alternative, another one is to use

   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907

More information about the R-help mailing list