在保持 class "numeric" 的同时控制 write.table 中的小数位数

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

一般来说,控制调用write.table时显示的位数很简单。鉴于 here 中出色的问答,我们认为 format 是实现这一壮举的手段。但是,这会创建一个文件,当用文本编辑器查看时,该文件会在数值周围显示引号。这可以通过在 write.table 中设置 quote = FALSE 来关闭。不幸的是,这具有不在 character 列周围放置引号的副作用。观察:

正常大小写(无格式和标准输出行为)

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"

write.table中的quote参数支持数值向量来指定要添加引号的列的位置,所以

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"