s-news
[Top] [All Lists]

Re: convert factor to numeric

To: "'carol white'" <wht_crl@yahoo.com>, <s-news@lists.biostat.wustl.edu>
Subject: Re: convert factor to numeric
From: "Alan Hochberg" <alan.hochberg@prosanos.com>
Date: Fri, 12 Oct 2007 11:30:57 -0400
In-reply-to: <899831.38241.qm@web62009.mail.re1.yahoo.com>
Thread-index: AcgM4YUVlswz+n6xQ6q8m2JGQ1O16QAATweA

Hello Carol,

 

Factors with levels which are numbers are a great source of confusion in R/S.  Here is an abbreviated example:

 

> size <- factor(c(9,12,26,22,24,13))

> size

[1] 9  12 26 22 24 13

 

So far so good, but internally, the “9” is stored as “factor level 1, corresponding to a levels attribute of 9”; the “12” is “factor level 2 for a levels attribute of 12”, etc.  The as.numeric() function ignores the levels attribute, and gives:

 

> as.numeric(size)

[1] 1 2 6 4 5 3

 

If you look at the levels attributes of your factor, they come out as character strings:

 

> levels(size)[size]

[1] "9"  "12" "26" "22" "24" "13"

 

So if you convert these to numeric, you get what you want:

 

> as.numeric(levels(size)[size])

[1]  9 12 26 22 24 13

 

Hope this helps,

 

Alan

 

Alan Hochberg

VP, Research

ProSanos Corporation

225 Market St. Ste. 502,

Harrisburg, PA 17101

Tel 717-635-2124 * Fax 717-635-2575

 

 

 

 

<Prev in Thread] Current Thread [Next in Thread>