我有这样的数据集
data <- data.frame(Time=as.Date(c("2007-01-31", "2007-02-28", "2007-03-31",
"2007-04-30", "2007-05-31"), format="%Y-%m-%d"),
a=c(104.8587, 104.5483, 104.0210, 105.7185, 104.9054),
b=c(95.4, 95.9, 95.6, 95.5, 95.8))
> data
Time a b
1 2007-01-31 104.8587 95.4
2 2007-02-28 104.5483 95.9
3 2007-03-31 104.0210 95.6
4 2007-04-30 105.7185 95.5
5 2007-05-31 104.9054 95.8
使用
ddata <- data.frame(diff(as.matrix(data[,-1])))
ddata$Time <- data[-1,1]
ddata <- ddata[c(3, 1:2)]
采取差异。
> ddata
Time a b
1 2007-02-28 -0.3104 0.5
2 2007-03-31 -0.5273 -0.3
3 2007-04-30 1.6975 -0.1
4 2007-05-31 -0.8131 0.3
然后我使用write.csv(ddata, file="ddata.csv", row.names=FALSE)
将其保存到csv文件中。但是,如果我重新加载它,值会改变。
> ddata <- read.table(file="ddata.csv", dec=",", header=T, sep=",")
> ddata
Time a b
1 2007-02-28 -0.310400000000001 0.5
2 2007-03-31 -0.527299999999997 -0.300000000000011
3 2007-04-30 1.69750000000001 -0.0999999999999943
4 2007-05-31 -0.813100000000006 0.299999999999997
舍入值仍然相同,但write.csv
命令添加了一些小数。发生什么事情了?
答案 0 :(得分:0)
您的write.csv操作,按原样导出数据,但略微舍入。
如果将数字设置为20,您会看到您认为-0.3实际上是-0.300000000000011369。
options(digits = 20)
ddata
Time a b
1 2007-02-28 -0.31040000000000134 0.500000000000000000
2 2007-03-31 -0.52729999999999677 -0.300000000000011369
3 2007-04-30 1.69750000000000512 -0.099999999999994316
4 2007-05-31 -0.81310000000000571 0.299999999999997158