[R] converting column to factor *within* a data frame

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 5 10:01:22 CET 2003


On Wed, 5 Nov 2003, Pascal A. Niklaus wrote:

> Hi all,
> 
> I repeatedly encounter the following problem: After importing a data set 
> into a data frame, I wish to set a column with numeric values to be a 
> factor, but can't figure out how to do this. Also, I do not wish to 
> write as.factor(x) all the time. I can create a new vector with x <- 
> factor(x), but the new vector resides outside the attached data frame.
> 
> Pascal
> 
>  > attach(ngrad)
>  > is.factor(STNW)
> [1] FALSE
> 
>  > ngrad$STNW<-factor(STNW)  ## doesn't work
>  > is.factor(STNW)
> [1] FALSE

It does work.  It changes ngrad, and not the copy you attached.

ngrad$STNW<-factor(ngrad$STNW)
attach(ngrad)

is the correct sequence.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list