一般来说,控制调用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"
答案 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"