Controlling number of decimal places in write.table while maintaining class “numeric”

若如初见. 提交于 2019-12-22 11:38:06

问题


Generally speaking, controlling the number of digits to display when calling write.table is straightforward. Given the excellent question and answer seen here, we see that format is the means to accomplish this feat. However, this creates a file that when viewed by a text editor, shows quotes around numeric values. This can be turned off by setting quote = FALSE in write.table. Unfortunately, this has the side effect of not putting quotations around character columns. Observe:

Normal Case (without format and standard output behavior)

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"

With Format

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"

With Quotes=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

Question

Is there a way to write a data frame to a file that controls the number of decimal places while maintaining the standard instructions of write.table for displaying quotes (i.e. no quotes around numeric fields and quotes around character fields)? Here is my desired output:

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

回答1:


The quote argument in write.table supports numeric vectors to specify the location of the columns to add quotes, so

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

works for this example, producing

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


来源:https://stackoverflow.com/questions/42032990/controlling-number-of-decimal-places-in-write-table-while-maintaining-class-num

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!