在保持类“数字”的同时控制write.table中的小数位数

时间:2017-02-03 21:02:40

标签: r write.table

一般来说,控制调用write.table时要显示的位数很简单。鉴于here出现的优秀问答,我们发现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"

1 个答案:

答案 0 :(得分:3)

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"