[R] help with as.numeric

Nutter, Benjamin NutterB at ccf.org
Fri May 15 14:36:04 CEST 2009

as.numeric() doesn't convert factors to the explicit value, nor should
it.  Under what you're expecting, ff you have a factor where the levels
are "Female" and "Male", using as.numeric() wouldn't produce anything

However, as.numeric() does something much smarter.  It converts "Female"
to 1, and "Male" to 2.  More generally, if you have n levels, it will
produce a vector of values between 1 and n.  This is referred to as the
'internal coding.'

If you want to convert your height and bmi variables to their numeric
values, you need to do

> as.numeric(as.character(height))

This will get you around the internal coding.

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of deanj2k
Sent: Friday, May 15, 2009 7:58 AM
To: r-help at r-project.org
Subject: [R] help with as.numeric

hi everyone, wondering if you could help me with a novice problem.  I
have a
data frame called subjects with a height and weight variable and want to
calculate a bmi variable from the two.  i have tried:

bmi <- (weight)/((height/100)^2)

but it comes up with the error:
Warning messages:
1: In Ops.factor(height, 100) : / not meaningful for factors
2: In Ops.factor((weight), ((height/100)^2)) :
  / not meaningful for factors

I presume that this means the vectors height and weight are not in
form (confirmed by is.numeric) so i changed the code to:

bmi <- (as.numeric(weight))/((as.numeric(height)/100)^2)

but this just comes up with a result which doesnt make sense i.e.
such as 40000 within bmi vector.  Ive looked at
as.numeric(height)/as.numeric(weight) and these numbers just arnt the
as height/weight which is the reason for the incorrect bmi.  Cant anyone
tell me where I am going wrong?  Its quiet frustrating because I cant
understand why a function claiming to convert to numeric would come up
such a bizarre result.
View this message in context:
Sent from the R help mailing list archive at Nabble.com.

R-help at r-project.org mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.


P Please consider the environment before printing this e-mail

Cleveland Clinic is ranked one of the top hospitals
in America by U.S. News & World Report (2008).  
Visit us online at http://www.clevelandclinic.org for
a complete listing of our services, staff and

Confidentiality Note:  This message is intended for use\...{{dropped:13}}

More information about the R-help mailing list