Raymont
Raymont

Reputation: 293

Data Convertion, from string to number

I have the following data

testing<-data.frame(price="1.165.338,00")

price   
1.165.338,00

price: Factor w/ 1 level "1.165.338,00": 1

How can I convert that price to 1165338.00 (numeric format with two decimals)?

I have tried with this formula:

as.numeric(gsub(",","",testing$price))*1000 

with no results

For the final formatting with 2 digits I would use:

 library(formattable)
 formattable(testing$price, digits = 2, format = "f")

Upvotes: 1

Views: 56

Answers (1)

xraynaud
xraynaud

Reputation: 2146

The problem comes from the dot that are used as a thousand separator and the comma as the decimal separator. One solution to do what you want is to 1/ remove the dots and than change the comma to a dot. Once done, the text can be converted to numeric using as.numeric(). For this to work, you have to specify the column name ($price):

as.numeric(sub(",",".",gsub(".","",as.character(testing$price),fixed=T)))

The fixed =T forces R to only replace '.' to '' (otherwise, '.' is a wildcard that matches to any single character).

To format the data to 2 digits numbers, you can use

format(x,nsmall=2)

Note that this converts the numbers back to characters.

Upvotes: 2

Related Questions