[R] apply and factor

Prof Brian D Ripley ripley at stats.ox.ac.uk
Fri Aug 10 08:37:53 CEST 2001


On Fri, 10 Aug 2001, Rachel Cunliffe wrote:

> Hi again
>
> Why does this occur?
>
> > test <- apply(data,2,factor)  # where data is a data.frame
> > is.factor(test[,1])
> [1] FALSE

test is a *matrix*, see ?apply.  No factors in matrices!

Using `data' as a name is probably a bad idea in R: it's an important
function name.

Try this

df <- data.frame(x=1:10, y=11:20)
test <- apply(df,2,factor)
is.factor(test[,1])
mode(test)
is.matrix(test)

The following should work (and does in S, so is a bug in R):
test2 <- df
test2[] <- lapply(df, factor)  # fails in R

but we need

test3 <- as.data.frame(lapply(df, factor))

(The difference arises if we had row names or other attributes.

row.names(df) <- letters[1:10]
test3 <- as.data.frame(lapply(df, factor)) #no row names

test2 <- df
test2[] <- lapply(df, factor) # keep row names

)


-- 
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 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list