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

Gavin Simpson gavin.simpson at ucl.ac.uk
Wed Oct 4 18:04:29 CEST 2006


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.
> 

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
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list