56

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

options(digits=3) 

并像这样列出data.frame。

ttf.all

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

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

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

看到漂亮的输出

> 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()

4

2 回答 2

61

You can use the function format() as in:

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

format() is a generic function that has methods for many classes, including data.frames. Unlike round(), it won't throw an error if your dataframe is not all numeric. For more details on the formatting options, see the help file via ?format

于 2013-01-12T19:47:24.050 回答
4

为具有混合列character的数据框添加解决方案。numeric我们首先用于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 包(v0.2.1.9000)于 2019-03-17 创建

于 2019-03-18T03:03:55.060 回答