[R] how to convert all columns of a data frame into factors

Gabor Grothendieck ggrothendieck at gmail.com
Wed Oct 4 18:31:29 CEST 2006


Just one small point on this.  This may not matter to you but
just in case it does, if L <- lapply(BOD, factor) then

replace(BOD, TRUE, L)
data.frame(L)

are not exactly the same in the case that BOD has additional
attributes (which in this case it does).  The first one will
preserve the attributes and the second one does not.

attributes(BOD)  # note reference attribute
attributes(replace(BOD, TRUE, L)  # reference preserved
attributes(data.frame(L))  # no reference


On 10/4/06, Gavin Simpson <gavin.simpson at ucl.ac.uk> wrote:
> On Wed, 2006-10-04 at 17:04 +0100, Gavin Simpson wrote:
> > On Wed, 2006-10-04 at 11:33 -0400, Weiwei Shi wrote:
> > > Hi,
> > >
> > > I use "apply"
> > > apply(x, 2, factor)
> > >
> > > but it does not work. please help. thanks.
> > >
>
> Ah, lesson one: read the email clearly before replying - just like my
> old Geography teacher used to tell me!
>
> This works
>
> dat <- sample(LETTERS, 100, replace = TRUE)
> # use a data. frame not a matrix
> dat <- data.frame(matrix(dat, ncol = 10))
> dat
> lapply(dat, factor) # as a list
> # or, as a data.frame
> data.frame(lapply(dat, factor))
>
> G
>
> >
> > In what sense does it not work? And how can you possibly expect anyone
> > on this list to help you as you neither supply the error message you
> > received nor provide us with x or a reproducible example, nor tell us
> > what you want to achieve.
> >
> > E.g.
> >
> > dat <- sample(LETTERS, 100, replace = TRUE)
> > dat <- matrix(dat, ncol = 10)
> > dat
> > apply(dat, 2, factor)
> >
> > which appears to be converting a character vector into a factor, which
> > is then coerced to a numeric vector (as there are only numeric and
> > character matrices in R) - but I may be wrong:
> >
> > as.numeric(factor(dat[,1]))
> >  [1] 7 7 2 5 8 1 4 7 3 6
> >
> > which is the first column of the object returned by apply(dat, 2,
> > factor). Is this not what you wanted?
> >
> > So perhaps you could provide the list with some further information as
> > you are asked to in the posting guide!
> >
> > HTH
> >
> > G
> --
> %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
>  Gavin Simpson                 [t] +44 (0)20 7679 0522
>  ECRC & ENSIS, UCL Geography,  [f] +44 (0)20 7679 0565
>  Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
>  Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
>  UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
> %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list