是否可以在 write.csv
中修复数字精度,比如 2 个十进制数字? ?如果是,是否可以在没有 .00
的情况下存储整数?在这种情况下?
谢谢!
最佳答案
不在 write.csv
或 write.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/