2016-08-06 144 views
1

我想利用這個數據幀如何指定R中寫入文件的數值的小數位數?

df <- data.frame(col1 = c(1.224, 1.3), col2 = c(0.8011, 1.90)) 

,並將其寫入一個文件,使每個數值正好顯示兩位小數。我試着在Controlling digits in R in write.csv給出的解決方案,但是當我使用

write.csv(format(df, digits = 2, nsmall = 2), "./testout.csv") 

在我的文件中的數值已轉換爲字符串。於是,我就在Formatting Decimal places in R給出的解決方案,具體如下:

write.csv(format(round(df, 2), nsmall = 2), "./testout.csv") 

但同樣,該文件顯示,我的數值已轉換爲字符串。

如何將這個data.frame寫入一個文件,以便將數值寫入爲精確到兩位小數的數值?

回答

2

您可以將quote=FALSE添加到您的write.csv調用中。

例如:

df[] <- lapply(df, sprintf, fmt='%.02f') 
write.csv(df, f <- tempfile(), row.names=FALSE, quote=FALSE) 
file.show(f) 
相關問題