Nathgun
Nathgun

Reputation: 125

only some characters change to numeric when converting in R

I need to convert the Votes column variable on the following data frame from character to numeric without adding NA’s

 > res
                  Party              Votes                  
 1 Progressive Liberal Party         28,599           
 2    Free National Movement         19,781           
 3 Commonwealth Labour Party            254            
 4              Independents            753            
 5       Invalid/blank votes                             
 6                     Total         49,387            

 > str(res)
'data.frame':   7 obs. of  5 variables:
$ Party: chr  "Progressive Liberal Party" "Free National Movement" 
"Commonwealth Labour Party" "Independents" ...
$ Votes: chr  "28,599" "19,781" "254" "753" ...

I have found this post on StackOverflow with a number of suggestions and I tried the following methods

How do I ensure that all numbers in the vote column are converted to numeric?

Upvotes: 1

Views: 196

Answers (2)

Sam Firke
Sam Firke

Reputation: 23014

To convert numbers that have commas, dollar signs, or similar formatting, use parse_number() from the readr package.

> library(readr)
> parse_number("28,599")
[1] 28599

Upvotes: 3

Eric Watt
Eric Watt

Reputation: 3230

The comma is throwing it off, you need to remove it first using gsub.

res$Votes <- as.numeric(gsub(",", "", res$Votes))

Upvotes: 1

Related Questions