rwjones
rwjones

Reputation: 377

Converting a factor to numeric in R

I know that variations of this question have been asked and answered, but I can't seem to get any to work for me.

I have a column labeled 'Interest.Rate', and the values are of this form: 12.75%

I tried:

as.numeric(as.character(loansData$Interest.Rate))

And what I got back was a screen full of 'NA's.

I suspect that I need to remove the '%' sign, but I'm not sure.

Any suggestions?

Upvotes: 0

Views: 283

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

You're right, you need to remove the '%' sign and then coerce the result to be numeric

> set.seed(1)
> Interest.Rate <- as.factor(paste0(sample(10), "%"))
> as.numeric(as.character(Interest.Rate))  # problem!!
 [1] NA NA NA NA NA NA NA NA NA NA

> as.numeric(gsub("\\%", "", Interest.Rate))  # solution
 [1]  3  4  5  7  2  8  9  6 10  1

Upvotes: 5

Related Questions