0

I am converting factors to numbers and have tried both solutions previously posted:

   as.numeric(as.character(factor))  
   as.numeric(levels(factor))

In both cases: I get lots of NA's and a warning message, NAs introduced by coercion. When I typed levels(factor), I do get many percentages (i.e. these are interest rates).

Is there any way I can convert these interest rates, whose class is factor, into numeric?

Thanks,

Shelley

agstudy
  • 119,832
  • 17
  • 199
  • 261
  • 2
    In order to answer with accuracy, we need to see your data and exactly what you're tried. However, I'm assuming you have factor levels such as "14" and "3.2%", and when you try to convert the levels to numbers, you get 14 and NA--right? You need to remove the "%". E.g.: `as.integer(gsub("\\D", "", "14%"))`. – Peyton Jul 02 '13 at 20:30
  • 1
    Welcome to StackOverflow! Could you please post some code, ideally a reproducible example with data? See http://stackoverflow.com/q/5963269/946850 for this. – krlmlr Jul 02 '13 at 20:32

1 Answers1

3

A "number" with percentage symbol is not considered as a numeric or integer in R, so you need to remove this symbol in every number first using for example gsub before doing the coercion.

perc <- factor(c("10%", "21.6%", "15%"))

as.numeric(as.character(perc))
[1] NA NA NA
Warning message:
NAs introduced by coercion 


as.numeric(gsub("\\%", "", perc))
[1] 10.0 21.6 15.0
dickoa
  • 18,217
  • 3
  • 36
  • 50