[R] convert factor dataframe into numeric matrix

John Kane jrkrideau at yahoo.ca
Wed Oct 24 16:36:19 CEST 2007


You might want to have a look at the two "R reference
card" documents under "Contributed" on CRAN. 

--- sun <flyhyena at yahoo.com.cn> wrote:

> 
> ----- Original Message ----- 
> From: "Prof Brian Ripley" <ripley at stats.ox.ac.uk>
> To: "sun" <flyhyena at yahoo.com.cn>
> Cc: <r-help at stat.math.ethz.ch>
> Sent: Wednesday, October 24, 2007 2:58 PM
> Subject: Re: [R] convert factor dataframe into
> numeric matrix
> 
> 
> > On Wed, 24 Oct 2007, sun wrote:
> >
> >> Bear me if this is a naive question.
> >>
> >> I have a dataframe, all lists inside it are
> factors. When I use
> >
> > Do you mean 'all columns are factors'?  A data
> frame is a list but usually 
> > does not contain lists.
> >
> >> as.matrix(df) to convert, I get a character
> matrix while my intention is 
> >> to
> >> get numeric matrix. I can make the convertion 
> iteratively by each list 
> >> but
> >> I do think there is some more elegant way of
> doing this.
> >>
> >> please let me know if I missed somthing there.
> >
> > ?data.matrix  may be what you are looking for: you
> gave us too little 
> > detail to be sure.
> >
> 
> 
> Thanks for your helps. I did not provide data 'cause
> I thought this is FAQ 
> type of question(maybe wrong impression).
> Actually I use algdesign generated a factorial
> design data frame in which:
> >
> > str(dat)
> 'data.frame':   2304 obs. of  6 variables:
>  $ party : Factor w/ 3 levels "1","2","3": 1 2 3 1 2
> 3 1 2 3 1 ...
>  $ dinner: Factor w/ 3 levels "1","2","3": 1 1 1 2 2
> 2 3 3 3 1 ...
>  $ d1    : Factor w/ 4 levels "1","2","3","4": 1 1 1
> 1 1 1 1 1 1 2 ...
>  $ p1    : Factor w/ 4 levels "1","2","3","4": 1 1 1
> 1 1 1 1 1 1 1 ...
>  $ d2    : Factor w/ 4 levels "1","2","3","4": 1 1 1
> 1 1 1 1 1 1 1 ...
>  $ p2    : Factor w/ 4 levels "1","2","3","4": 1 1 1
> 1 1 1 1 1 1 1 ...
> 
> I just figured out a way fo convert it to numeric
> matrix using
> >d = as.data.frame(lapply(dat,as.numeric))
> 
> but "data.matrix()" suggested by Prof. Brian and Mr.
> Dimitris is exactly the 
> thing I was looking for.
> 
> I am not sure if there exist some documents or
> online source that have 
> documented these kind of "utility functions"
> categorized in somet categories 
> like "data types", "data manipulating functions",
> "variable scopes", etc., 
> that allow a quick browsing for some functions or
> other information.
> 
> Thanks for your kind helps.
> 
> Kind regards,
> Sun
> 
> ______________________________________________
> R-help at r-project.org 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