2017-02-03 96 views
2

一般來說,控制調用write.table時要顯示的位數很簡單。鑑於出色的問題和答案見here,我們看到format是完成這一壯舉的手段。但是,這會創建一個文件,在文本編輯器中查看時,會顯示數字值的引號。這可以通過在write.table中設置quote = FALSE來關閉。不幸的是,這有一個副作用,就是不會在character列中加上引號。觀察:控制write.table中的小數位數,同時保持「數字」類

正常情況(無格式和標準輸出行爲)

df <- data.frame(c1 = 1:5/100, c2 = LETTERS[1:5]) 
write.table(df, file = "test.txt", sep = "|") 

## when you open test.txt in a text editor, the middle column correctly 
## appears as a numeric (i.e. no quotes), however there are only 2 decimals displayed. 
## It should also be noted that the quotes are present in c2 (this is what we want). 
    "c1"|"c2" 
"1"|0.01|"A" 
"2"|0.02|"B" 
"3"|0.03|"C" 
"4"|0.04|"D" 
"5"|0.05|"E" 

隨着格式

df$c1 <- format(df$c1, digits = 4, nsmall = 4) 
write.table(df, file = "test.txt", sep = "|") 

## when you open test.txt in a text editor, the middle column correctly 
## displays four decimal places, however it now appears to be a character 
## (i.e. with quotes). Again, it should be noted that the quotes are 
## present in c2 (again, this is what we want). 
    "c1" |"c2" 
"1"|"0.0100"|"A" 
"2"|"0.0200"|"B" 
"3"|"0.0300"|"C" 
"4"|"0.0400"|"D" 
"5"|"0.0500"|"E" 

隨着行情= FALSE

write.table(df, file = "test.txt", sep = "|", quote = FALSE) 

## when you open test.txt in a text editor, the middle column correctly 
## displays four decimal places with no quotes. However the quotes on column 
## c2 (and everywhere else) have been dropped (this is NOT what we want). 
    c1 |c2 
1|0.0100|A 
2|0.0200|B 
3|0.0300|C 
4|0.0400|D 
5|0.0500|E 

問題

有沒有辦法將數據幀寫入控制小數位數的文件中,同時保持標準指令write.table用於顯示引號(即,數字字段和字符字段周圍沒有引號)?這是我想要的輸出:

 "c1" |"c2" 
"1"|0.0100|"A" 
"2"|0.0200|"B" 
"3"|0.0300|"C" 
"4"|0.0400|"D" 
"5"|0.0500|"E" 
+0

在寫表之前使用'round()'會有幫助嗎? –

回答

3

write.table的報價參數支持數字矢量指定列的位置添加引號,所以

write.table(df, file = "test.txt", sep = "|", quote = 2) 

作品在這個例子中,產生

"c1"|"c2" 
"1"|0.01|"A" 
"2"|0.02|"B" 
"3"|0.03|"C" 
"4"|0.04|"D" 
"5"|0.05|"E"