如何控制write.table()输出中的小数位数?

use*_*rJT 52 excel r decimal-point number-formatting output-formatting

在处理数据时(例如,在data.frame中),用户可以通过使用来控制显示数字

options(digits=3) 
Run Code Online (Sandbox Code Playgroud)

并列出data.frame这样的.

ttf.all
Run Code Online (Sandbox Code Playgroud)

当用户需要像这样在Excell中粘贴数据时

write.table(ttf.all, 'clipboard', sep='\t',row.names=F)
Run Code Online (Sandbox Code Playgroud)

数字参数被忽略,数字不会舍入.

看到好的输出

> ttf.all
  year V1.x.x V1.y.x ratio1 V1.x.y V1.y.y ratioR V1.x.x V1.y.x ratioAL V1.x.y V1.y.y ratioRL
1 2006    227    645   35.2     67    645   10.4    150    645    23.3     53    645    8.22
2 2007    639   1645   38.8    292   1645   17.8    384   1645    23.3    137   1645    8.33
3 2008   1531   3150   48.6    982   3150   31.2    755   3150    24.0    235   3150    7.46
4 2009   1625   3467   46.9   1026   3467   29.6    779   3467    22.5    222   3467    6.40
Run Code Online (Sandbox Code Playgroud)

但excel(剪贴板)中的内容并非四舍五入.如何控制write.table()

Mat*_*agg 55

您可以使用以下功能format():

write.table(format(ttf.all, digits=2), 'clipboard', sep='\t',row.names=F)
Run Code Online (Sandbox Code Playgroud)

format()是一个泛型函数,具有许多类的方法,包括data.frames.round()与之不同,如果您的数据帧不是全数字,它不会抛出错误.有关格式化选项的更多详细信息,请参阅帮助文件?format

  • 当我同时使用`digits = 2`和`scientific = F`时,忽略数字设置.如果我允许科学,它工作正常.有任何想法吗? (3认同)