一般来说,控制呼叫时显示的位数 write.table
很简单。鉴于此处看到的出色问答,我们认为这format
是完成这一壮举的手段。但是,这会创建一个文件,当由文本编辑器查看时,会在数值周围显示引号。quote = FALSE
这可以通过设置来关闭write.table
。不幸的是,这样做的副作用是不在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"