格式化R中的小数位 [英] Formatting Decimal places in R

查看:494
本文介绍了格式化R中的小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字,例如1.128347132904321674821,当输出到屏幕(或写入文件)时,我想只显示两位小数。一个人怎么做?

  x < -  1.128347132904321674821 

编辑:

使用:

  options(digits = 2)

已被建议作为可能的答案。有一种方法可以在脚本中指定一次性使用吗?当我将它添加到我的脚本中时,它似乎没有做任何不同的事情,我不想重新输入格式化每个数字(我自动化一个非常大的报告)。

< - > -

回答:round(x,digits = 2)

解决方案

背景:在此页面上建议的一些答案(例如 signif options(digits = ...))不保证显示任意数字的小数位数。我认为这是R中的一个设计特征,其中良好的科学实践涉及根据原则显示一定数量的数字有效数字。然而,在许多领域(例如, APA风格,业务报告)格式化要求规定显示一定数量的小数位数。这通常是为了一致性和标准化的目的,而不是关注重要数字。

解决方案

下面的代码显示了数字 x 的精确到位的两位小数。

 格式(round(x,2),nsmall = 2)



$ p $ format(round(1.20,2),nsmall = 2)
#[1]1.20
格式(round(1,2),nsmall = 2)
#[1]1.00
格式(round(1.1234,2),nsmall = 2)
# 1]1.12

更一般的函数如下所示,其中 x 是数字, k 是显示的小数位数。 trimws 删除任何前导空格,如果您有一个向量的数字,那么这个空格是有用的。

  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


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"

这篇关于格式化R中的小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆