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

Philippe Glaziou glaziou at pasteur-kh.org
Wed Nov 5 11:01:48 CET 2003


Pascal A. Niklaus <Pascal.Niklaus at unibas.ch> wrote:
> 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

That command checked the attached dataset, which has not been
modified by the previous command. You seem to be confused by what
attach() does. Read ?attach.

> data <- data.frame(a=1:3, b=4:6)
> data
  a b
1 1 4
2 2 5
3 3 6
> attach(data)
> is.factor(a)
[1] FALSE
> data$a <- as.factor(a)
> is.factor(a)
[1] FALSE
> is.factor(data$a)
[1] TRUE
> detach(data)
> attach(data)
> is.factor(a)
[1] TRUE

-- 
Philippe




More information about the R-help mailing list