使用千位分隔符将字符更改为data.frame(as.numeric)中的数字 [英] Changing character to numeric in data.frame (as.numeric) with thousand separator

查看:49
本文介绍了使用千位分隔符将字符更改为data.frame(as.numeric)中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 read.csv 导入了一个带有数字值的CSV文件,其中CSV分隔符为;",小数点分隔符为,",另外,thousend分隔符为."

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)

我将其转换为data.table ...

I transformed it in a data.table ...

Hist <- data.table(Hist)

它看起来像这样:

  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)]

正在创建错误:

警告信息:在eval(jsub,SDenv,parent.frame())中:强制引入的NAs

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

有人可以帮忙吗?

推荐答案

它们被视为字符串.为了将它们转换为数字,请删除千位分隔符(.),然后将小数点分隔符(,)转换为点.

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))))

与以下相同:

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

这篇关于使用千位分隔符将字符更改为data.frame(as.numeric)中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆