【问题标题】:How to control number of decimal digits in write.table() output?如何控制 write.table() 输出中的小数位数?
【发布时间】:2012-12-25 00:01:42
【问题描述】:

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

options(digits=3) 

并像这样列出data.frame。

ttf.all

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

write.table(ttf.all, 'clipboard', sep='\t',row.names=F)

digits 参数被忽略,数字不四舍五入。

查看漂亮的输出

> 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

但是 excel(剪贴板)中的内容不是四舍五入的。在write.table()如何控制?

【问题讨论】:

  • 使用round()...
  • 如果我理解正确,round() 必须应用于一组列,我必须列举这些列。 digits=3 是全局的,不需要列枚举。所以 round() 不是一个完美的解决方案。

标签: r excel number-formatting decimal-point output-formatting


【解决方案1】:

你可以使用函数format()如下:

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

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

【讨论】:

  • 当我同时使用digits=2scientific=F 时,将忽略数字设置。如果我允许科学,它工作正常。有什么想法吗?
  • 亲爱的@jzadra 在我的情况下,有一个长科学数字与较小数字混合的数据框,我使用这些选项来正确查看 R 数字,以及将数据正确保存在 csv 文件中,正如我在 R 中看到的那样:general R option : options(scipen=1, digits=8), and for write.table(format(data_table, digits=4, scientific=F)
  • 以某种方式,通过在一般R环境中设置要显示的小数位数,将其传递给写表命令,得到没有十进制数的数字!因此,write.table中的小数位数必须相对增加。
  • character 转换可能很慢,所以这并不理想
  • 使用write.table(format(1.019, digits=2), file= paste0(getwd(), "/test.csv")),例如,给了我一个值为1的.csv,我希望1.02
【解决方案2】:

为具有混合 characternumeric 列的数据框添加解决方案。我们首先使用mutate_if 选择numeric 列,然后对它们应用round() 函数。

# install.packages('dplyr', dependencies = TRUE)
library(dplyr)

df <- read.table(text = "id  year V1.x.x V1.y.x ratio1
a 2006    227.11111    645.11111   35.22222  
b 2007    639.11111   1645.11111   38.22222  
c 2008   1531.11111   3150.11111   48.22222  
d 2009   1625.11111   3467.11111   46.22222",
                 header = TRUE, stringsAsFactors = FALSE)

df %>% 
  mutate_if(is.numeric, round, digits = 2)
#>   id year  V1.x.x  V1.y.x ratio1
#> 1  a 2006  227.11  645.11  35.22
#> 2  b 2007  639.11 1645.11  38.22
#> 3  c 2008 1531.11 3150.11  48.22
#> 4  d 2009 1625.11 3467.11  46.22

### dplyr v1.0.0+
df %>% 
  mutate(across(where(is.numeric), ~ round(., digits = 2)))
#>   id year  V1.x.x  V1.y.x ratio1
#> 1  a 2006  227.11  645.11  35.22
#> 2  b 2007  639.11 1645.11  38.22
#> 3  c 2008 1531.11 3150.11  48.22
#> 4  d 2009 1625.11 3467.11  46.22

reprex package (v0.2.1.9000) 于 2019-03-17 创建

【讨论】:

    猜你喜欢
    • 2017-06-21
    • 1970-01-01
    • 2015-08-29
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多