是否有数据类型“十进制"?在R中? [英] Is there a datatype "Decimal" in R?
问题描述
我从MySQL表读取以DECIMAL
格式存储的数据.我想对R中的这些数字进行计算.
I read data stored in the format DECIMAL
from a MySQL-Table. I want to do calculations on those numbers within R.
我曾经使用as.numeric()
将它们转换为数字表示形式,但是文档中说:
I used to cast them to a numeri represaentation using as.numeric()
, but the documentation says:
数字等于双精度(实数).
numeric is identical to double (and real).
但是R中是否还有数据类型Decimal? (没有舍入错误的数据类型,...)
But is there also a datatype Decimal in R? (Datatype without rounding errors,...)
这里是一个简单的示例,说明存在舍入错误的问题:
Here a simple example for the problem with rounding errors:
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
推荐答案
您可以创建自己的:
d <- structure( list(i=589L,exp=2L), class="decimal" )
print.decimal <- function( x, ...) print( x$i * 10^(-x$exp) )
> d
[1] 5.89
实际上,某些大型软件包也可能适用于此,因为它们使用类似的表示方式....
Actually, some of the big number packages may work for this as well, since they use a similar representation....
这篇关于是否有数据类型“十进制"?在R中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!