简体   繁体   English

使用千位分隔符将字符更改为data.frame(数字形式)中的数字

[英]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 "." 我使用read.csv导入了带有数字值的CSV文件,其中CSV分隔符为“;”,十进制分隔符为“,”,另外,thousend分隔符为“。”。

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

I transformed it in a data.table ... 我将其转换为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 警告消息:在eval(jsub,SDenv,parent.frame())中:强制引入的NA

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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