我想将一个矢量写入文件,然后使用Rstudio读取它。向量包含一些大整数(数字大小为10 ^ 40),似乎它无法正确写入,因为当我想要读它时,我一直收到这些错误:
" ReadList :: readn:从" /Users/Research/RF_improvment/testNTT.txt读取时找到的实数无效。"
和
" Part :: partw:{$ Failed}的第1025部分不存在。 Set :: partw:{Mod [$ Failed + {$ Failed} [[1025]]的第1025部分,115792089237316195423570985008687907853269984665640564039457584007913129461761]}不存在。"
有人知道如何使用R中的写入函数将大数字写入文件吗?我没有计算问题,错误是读取和写入文件。
答案 0 :(得分:1)
可以使用以下方式找到可以使用的最大整数R:
> .Machine$integer.max
# [1] 2147483647
>
因此,R中的写入或读取函数不能处理如此大小的整数:
# So when you compute large numbers using R
# they are computed with double precision:
options("scipen"=400, "digits"=4)
anum <- 10^40
bnum <- 9^40
# The above numbers are no longer integers,
# but rather floating values calculated with double precision:
str(anum)
num 10000000000000000304008240626848262428282
如果使用某些包计算大整数幂,结果实际上不是整数:
library(gmp)
bigN <- as.bigz(2)^40
bigN
# Big Integer ('bigz') :
# [1] 1099511627776
str(bigN)
# Class 'bigz' raw [1:20] 01 00 00 00 ...
如果目标是将这些值保存到文本文件中然后再读回来,那么可以采取以下方法:
# Create "big" numbers using gmp package
library(gmp)
bigA <- as.bigz(10)^40
bigB <- as.bigz(9)^40
bigA
# Big Integer ('bigz') :
# [1] 10000000000000000000000000000000000000000
#Save them as character vector:
# write them to a file
write.csv(data.frame(a=as.character(bigA), b=as.character(bigB)), "myfile.csv", row.names=FALSE)
# Let's take a look at the file
system("cat myfile.csv")
#"a","b"
#"10000000000000000000000000000000000000000","147808829414345923316083210206383297601"
# Read them back as a character strings first.
new.dt <- read.csv("myfile.csv", colClasses=c("character","character"))
str(new.dt)
# 'data.frame': 1 obs. of 2 variables:
# $ a: chr "10000000000000000000000000000000000000000"
# $ b: chr "147808829414345923316083210206383297601"
# Convert them back to "bigz" objects:
bigA.new <- as.bigz(new.dt$a)
bigB.new <- as.bigz(new.dt$b)
bigA
#Big Integer ('bigz') :
# [1] 10000000000000000000000000000000000000000