简体   繁体   中英

Changing character to numeric in data.frame (as.numeric) with thousand separator

I used read.csv to import a CSV file with numeric values where the CSV seperator is ";", the decimal seperator is "," and additional the thousend seperator is "."

Hist <- read.csv(file = "XXXX", header = T, sep = ";", dec =",", stringsAsFactors=FALSE)

I transformed it in a data.table ...

Hist <- data.table(Hist)

And it looks like this:

  Date        Value
# 2017-11-12  12.456,89
# 2017-11-10  13.234,99
# 2017-11-08  14.123,45

Now I want to change the class/format of the column "Value" to numeric since I want to calculate with it. But everything I tried did not worked. For example:

Hist[, Value := as.numeric(Value)]

is creating the error:

Warning message: In eval(jsub, SDenv, parent.frame()) : NAs introduced by coercion

Can anybody help?

They are read as strings. In order to convert them to a number remove the thousands separator (.) and then convert the decimal separator (,) to a point.

Hist$Value = as.numeric(gsub(",",".",(gsub("\\.","",Hist$Value))))

Which is the same as:

noPoints = gsub("\\.", "", Hist$Value)
commaToPoint = gsub(",", ".", noPoints)
Hist$Value = as.numeric(commaToPoint)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM