[R] conversion of a data.frame of numerics to a data.frame of factors
Patrick Giraudoux
patrick.giraudoux at univ-fcomte.fr
Sat Oct 9 17:02:20 CEST 2004
This work perfectly with a data.frame. Actually my so-called "data.frame" was an output of t(), and thus not a data.frame (what I
realise after trying Prof. Ripley's example). If applied to an output of t() (eg t(df)), the result is quite unxpected (to me): a
strange list of 989 elements, each of them being a factor of one digit and one level corresponding to each cell of the matrix 23
rows x 43 columns...
So in this particular case, advised to write:
mydf<-as.data.frame(t(mydf0))
mydf[] <- lapply(mydf, as.factor)
> ----- Original Message -----
> From: "Prof Brian Ripley" <ripley at stats.ox.ac.uk>
> To: "Patrick Giraudoux" <patrick.giraudoux at univ-fcomte.fr>
> Cc: "r-help" <r-help at stat.math.ethz.ch>
> Sent: Saturday, October 09, 2004 4:32 PM
> Subject: Re: [R] conversion of a data.frame of numerics to a data.frame of factors
>
>
> > On Sat, 9 Oct 2004, Patrick Giraudoux wrote:
> >
> > mydf[] <- lapply(mydf, as.factor)
> >
> > would appear to be what you want.
> >
> > For a matrix, I presume you want a factor matrix as the result. Something
> > like
> >
> > my <- matrix(1:12, 3, 4)
> > dmy <- dim(my)
> > my <- as.factor(my)
> > dim(my) <- dmy
> > my
> >
> > which does not print as a matrix but is one. If you want a data frame
> > result, convert to a data frame first.
> >
> > > Hi,
> > >
> > > I am trying to convert a data.frame of numerics (this could be a matrix
> > > as well in this case) into a data.frame of factors.
> > >
> > > I did it in a way that is less than direct...
> > >
> > > myforet2<-t(myforet)
> > > for (i in 1:length(myforet2[1,])) {
> > > if (i == 1)myforetfact<-list(as.factor(myforet2[,i]))
> > > else myforetfact<-c(myforetfact,list(as.factor(myforet2[,i])))
> > > }
> > > myforetfact<-data.frame(myforetfact)
> > > names(myforetfact)<-row.names(myforet)
> > >
> > > Here again, I wonder if there are no easier way to go through.... (the loop is not "R" style, for the least). However, I
cannot
> do
> > > it otherway so far...
> > >
> > > Cheers,
> > >
> > > Patrick
> > >
> > > ______________________________________________
> > > 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
> > >
> > >
> >
> > --
> > 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