I have a number, for example 1.128347132904321674821 that I would like to show as only two decimal places when output to screen (or written to a file). How does one do that?

x <- 1.128347132904321674821

EDIT:

The use of:

options(digits=2)

Has been suggested as a possible answer. Is there a way to specify this within a script for one-time use? When I add it to my script it doesn't seem to do anything different and I'm not interested in a lot of re-typing to format each number (I'm automating a very large report).

--

Answer: round(x, digits=2)

推荐答案

Background: Some answers suggested on this page (e.g., signif, options(digits=...)) do not guarantee that a certain number of decimals are displayed for an arbitrary number. I presume this is a design feature in R whereby good scientific practice involves showing a certain number of digits based on principles of "significant figures". However, in many domains (e.g., APA style, business reports) formatting requirements dictate that a certain number of decimal places are displayed. This is often done for consistency and standardisation purposes rather than being concerned with significant figures.

Solution:

The following code shows exactly two decimal places for the number x.

format(round(x, 2), nsmall = 2)

For example:

format(round(1.20, 2), nsmall = 2)
# [1] "1.20"
format(round(1, 2), nsmall = 2)
# [1] "1.00"
format(round(1.1234, 2), nsmall = 2)
# [1] "1.12"

A more general function is as follows where x is the number and k is the number of decimals to show. trimws removes any leading white space which can be useful if you have a vector of numbers.

specify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))

E.g.,

specify_decimal(1234, 5)
# [1] "1234.00000"
specify_decimal(0.1234, 5)
# [1] "0.12340"

Discussion of alternatives:

The formatC answers and sprintf answers work fairly well. But they will show negative zeros in some cases which may be unwanted. I.e.,

formatC(c(-0.001), digits = 2, format = "f")
# [1] "-0.00"
sprintf(-0.001, fmt = '%#.2f')
# [1] "-0.00"

One possible workaround to this is as follows:

formatC(as.numeric(as.character(round(-.001, 2))), digits = 2, format = "f")
# [1] "0.00" 

R相关问答推荐

删除facet_wrap标签之间的水平线

更改编号列表的 colored颜色

如何从R中的字符串元素中减go 一个数字?

如何动态更新selectizeInput?

将数据集中的值增加到当前包含的最大值

在rpart. plot或fancyRpartPlot中使用带有下标的希腊字母作为标签?

将重复项转换为NA

绘制采样开始和采样结束之间的事件

将Posict转换为数字时的负时间(以秒为单位)

如何从容器函数中提取conf并添加到ggplot2中?

如果COLSUM为>;0,则COLNAME为向量

如何在R中改变fviz_pca_biplot中圆的边界线的 colored颜色 ?

为什么这个表格格罗布不打印?

防止在更新SHINY中的Reactive Value的部分内容时触发依赖事件

通过初始的shiny 应用更新部署的shiny 应用的数据和参数,其中部署的应用程序显示为URL

Rmarkdown::Render vs Source()

SHILINY中DT列的条件着色

基于R中的辅助向量中的值有条件地连接向量中的字符串

构建一个6/49彩票模拟系统

对一个数据帧中另一个数据帧中的值进行计数