How to control number of decimal digits in write.table() output?

混江龙づ霸主 提交于 2019-11-30 01:10:51

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

Adding a solution for data frame having mixed character and numeric columns. We first use mutate_if to select numeric columns then apply the round() function to them.

# 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)
str(df)
#> 'data.frame':    4 obs. of  5 variables:
#>  $ id    : chr  "a" "b" "c" "d"
#>  $ year  : int  2006 2007 2008 2009
#>  $ V1.x.x: num  227 639 1531 1625
#>  $ V1.y.x: num  645 1645 3150 3467
#>  $ ratio1: num  35.2 38.2 48.2 46.2


df <- df %>% 
  mutate_if(is.numeric, round, digits = 2)
df
#>   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

Created on 2019-03-17 by the reprex package (v0.2.1.9000)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!