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

Gabor Grothendieck ggrothendieck at gmail.com
Tue Jun 27 12:54:02 CEST 2006


On 27 Jun 2006 12:31:10 +0200, Peter Dalgaard <p.dalgaard at biostat.ku.dk> wrote:
> 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
> transform().
>

transform is probably the best but if you reallly want to use 'with' :

   xxx[c("x", "y")] <- with(xxx, list(as.character(x), as.numeric(y)))

or the following two if there are no additional columns in xxx:

   xxx[] <- with(xxx, list(as.character(x), as.numeric(y)))

   xxx <- with(xxx, data.frame(x = as.character(x), y = as.numeric(y)))



More information about the R-help mailing list