R - 具有固定精度的 write.csv

标签 r precision

是否可以在 write.csv 中修复数字精度,比如 2 个十进制数字? ?如果是,是否可以在没有 .00 的情况下存储整数?在这种情况下?
谢谢!

最佳答案

不在 write.csvwrite.table本身。来自帮助文档( ?write.table ):

In almost all cases the conversion of numeric quantities is governed by the option '"scipen"' (see 'options'), but with the internal equivalent of 'digits = 15'. For finer control, use 'format' to make a character matrix/data frame, and call 'write.table' on that.



您最好使用 format 自己格式化列。 ,唉:
set.seed(42)
df1 <- data.frame(x = runif(10), y = sample(10))
df1$x <- round(df1$x, digits = 2)
write.csv(df1, ...)

编辑 :

为了漂亮地打印到屏幕上,只需使用 options(digits = 2)并再次转储 data.frame。我猜你想漂亮地打印到 CSV 中,所以......

使用以下函数:
dfDigits <- function(x, digits = 2) {
    ## x is a data.frame
    for (col in colnames(x)[sapply(x, class) == 'numeric'])
        x[,col] <- round(x[,col], digits = digits)
    x
}
set.seed(42)
df1 <- data.frame(x=runif(5),y=sample(5))
head(df1)
##              x y
## 1 0.9148060435 3
## 2 0.9370754133 5
## 3 0.2861395348 1
## 4 0.8304476261 2
## 5 0.6417455189 4
head(dfDigits(df1, 2))
##      x y
## 1 0.91 3
## 2 0.94 5
## 3 0.29 1
## 4 0.83 2
## 5 0.64 4

关于R - 具有固定精度的 write.csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29352659/

相关文章:

python - 在 R 中做 dt[,y :=myfun(x), by=list(a,b,c)] 的 pythonic 方法是什么?

r - 使用子目录使用 knitr

c++ - 对称的Lerp和编译器优化

c - 理解从整数到 float 的转换

c++ - 我在 IEEE754 乘法中失去了 2 的幂

python - 具有更高时间精度的 gnuplot 替代方案

r - 如何解决 R 估计中的整数溢出错误

r - 微基准 : Pass a variable to the function

r - 抑制打印到屏幕的平稳性测试的输出

c++ - 机器 Epsilon 精度差异