在 R 中格式化小数位 [英] Formatting Decimal places in R
问题描述
我有一个数字,例如 1.128347132904321674821,我想在输出到屏幕(或写入文件)时只显示两位小数.如何做到这一点?
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
使用:
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).
--
答案:round(x,digits=2)
Answer: round(x, digits=2)
推荐答案
背景: 本页建议的一些答案(例如,signif
、options(digits=...)
) 不保证为任意数字显示一定数量的小数.我认为这是 R 中的一个设计功能,良好的科学实践涉及根据 原则显示一定数量的数字有效数字".然而,在许多领域(例如,APA 风格,商业报告)格式要求规定显示一定数量的小数位.这样做通常是为了一致性和标准化目的,而不是关注有效数字.
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.
解决方案:
以下代码正好显示了数字 x
的两位小数.
The following code shows exactly two decimal places for the number x
.
format(round(x, 2), nsmall = 2)
例如:
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"
更通用的函数如下,其中 x
是数字,k
是要显示的小数位数.trimws
删除任何前导空格,如果您有数字向量,这可能很有用.
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))
例如,
specify_decimal(1234, 5)
# [1] "1234.00000"
specify_decimal(0.1234, 5)
# [1] "0.12340"
这篇关于在 R 中格式化小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!