首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R中有数据类型"Decimal“吗?

问R中有数据类型"Decimal“吗?
EN

Stack Overflow用户
提问于 2013-06-06 10:48:48
回答 2查看 6.1K关注 0票数 18

我从MySQL读取以DECIMAL格式存储的数据。我想在R中对这些数字进行计算。

我以前使用as.numeric()将它们转换成数字表示,但是文档中说:

数字与双(和实)相同。

但是在R中也有数据类型的十进制吗?(数据类型没有舍入错误,.)

这里是舍入错误问题的一个简单示例:

代码语言:javascript
复制
numbersStrings = c("0.1", "0.9")
numbersNumeric = as.numeric(numbersStrings)
numbersMirror  = c(numbersNumeric, 1-numbersNumeric)

str(numbersMirror)

numbersMirror
unique(numbersMirror)  # has two times 0.1 ...

sprintf("%.25f", numbersMirror)
sprintf("%.25f", unique(numbersMirror))  # ... because there was a rounding error
EN

回答 2

Stack Overflow用户

发布于 2013-06-06 12:19:09

你可以自己创造:

代码语言:javascript
复制
d <- structure( list(i=589L,exp=2L), class="decimal" )
print.decimal <- function( x, ...) print( x$i * 10^(-x$exp) )
> d
[1] 5.89

实际上,一些大数目的包也可能适用于此,因为它们使用类似的表示形式.

票数 4
EN

Stack Overflow用户

发布于 2016-09-01 09:38:59

类似于Ari应答的方法,但使用了来自bit64包的bit64类。在各种不支持十进制类型的应用程序中,使用大int作为基础数据类型是常见的做法。

​

代码语言:javascript
复制
library(bit64)

as.decimal = function(x, p=2L) structure(as.integer64(x*10^p), class="decimal", precision=p)
print.decimal = function(x) print(as.double(x))
as.integer64.decimal = function(x) structure(x, class="integer64", precision=NULL) # this should not be exported
as.double.decimal = function(x) as.integer64(x)/(10^attr(x, "precision"))
is.decimal = function(x) inherits(x, "decimal")
"==.decimal" = function(e1, e2) `==`(as.integer64(e1), as.integer64(e2))
"+.decimal" = function(e1, e2) `+`(as.integer64(e1), as.integer64(e2))

d = as.decimal(12.69)
is.decimal(d)
#[1] TRUE
print(d)
#[1] 12.69
as.double(d)
#[1] 12.69
d + as.decimal(0.9)
#[1] 13.59
0.1 + 0.2 == 0.3
#[1] FALSE
as.decimal(0.1) + as.decimal(0.2) == as.decimal(0.3)
#[1] TRUE
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16960167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档