R 中小数位的格式

发布于 2024-09-13 22:49:23 字数 349 浏览 9 评论 0原文

我有一个数字,例如 1.128347132904321674821,我想在输出到屏幕(或写入文件)时仅显示两位小数。如何做到这一点?

x <- 1.128347132904321674821

编辑:

使用:

options(digits=2)

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

--

答案:round(x, 数字=2)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

自此以后,行同陌路 2024-09-20 22:49:23

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

解决方案

以下代码精确显示数字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 删除所有前导空格,如果您有数字向量,这会很有用。

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"

替代方案的讨论

formatC 答案sprintf 答案 效果相当好。但在某些情况下它们会显示负零,这可能是不需要的。即,

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

一种可能的解决方法如下:

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

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" 
指尖微凉心微凉 2024-09-20 22:49:23

您可以根据需要设置数字的格式,例如 x,最多可达小数位。这里x是一个有很多小数位的数字。假设我们希望显示该数字最多 8 位小数:

x = 1111111234.6547389758965789345
y = formatC(x, digits = 8, format = "f")
# [1] "1111111234.65473890"

这里 format="f" 给出了通常小数位的浮点数,例如 xxx.xxx 和 digits指定位数。相比之下,如果您想显示一个整数,则可以使用 format="d" (很像 sprintf)。

You can format a number, say x, up to decimal places as you wish. Here x is a number with many decimal places. Suppose we wish to show up to 8 decimal places of this number:

x = 1111111234.6547389758965789345
y = formatC(x, digits = 8, format = "f")
# [1] "1111111234.65473890"

Here format="f" gives floating numbers in the usual decimal places say, xxx.xxx, and digits specifies the number of digits. By contrast, if you wanted to get an integer to display you would use format="d" (much like sprintf).

鹿港巷口少年归 2024-09-20 22:49:23

你可以试试我的包formattable

> # devtools::install_github("renkun-ken/formattable")
> library(formattable)
> x <- formattable(1.128347132904321674821, digits = 2, format = "f")
> x
[1] 1.13

好处是,x 仍然是一个数字向量,您可以使用相同的格式进行更多计算。

> x + 1
[1] 2.13

更好的是,数字不会丢失,您可以随时使用更多数字重新格式化:)

> formattable(x, digits = 6, format = "f")
[1] 1.128347

You can try my package formattable.

> # devtools::install_github("renkun-ken/formattable")
> library(formattable)
> x <- formattable(1.128347132904321674821, digits = 2, format = "f")
> x
[1] 1.13

The good thing is, x is still a numeric vector and you can do more calculations with the same formatting.

> x + 1
[1] 2.13

Even better, the digits are not lost, you can reformat with more digits any time :)

> formattable(x, digits = 6, format = "f")
[1] 1.128347
甜嗑 2024-09-20 22:49:23

对于 2 个小数位,假设您想要保留尾随零

sprintf(5.5, fmt = '%#.2f')

,这给出了

[1] "5.50"

正如 @mpag 下面提到的,似乎 R 有时可以使用此方法和舍入方法给出意外的值,例如 sprintf(5.5550, fmt='%#.2f') 给出 5.55 ,不是 5.56

for 2 decimal places assuming that you want to keep trailing zeros

sprintf(5.5, fmt = '%#.2f')

which gives

[1] "5.50"

As @mpag mentions below, it seems R can sometimes give unexpected values with this and the round method e.g. sprintf(5.5550, fmt='%#.2f') gives 5.55, not 5.56

病毒体 2024-09-20 22:49:23

类似的东西:

options(digits=2)

数字选项的定义:

digits: controls the number of digits to print when printing numeric values.

Something like that :

options(digits=2)

Definition of digits option :

digits: controls the number of digits to print when printing numeric values.
神回复 2024-09-20 22:49:23

如果您更喜欢有效数字而不是固定数字,则使用 signif 命令可能有用:

> signif(1.12345, digits = 3)
[1] 1.12
> signif(12.12345, digits = 3)
[1] 12.1
> signif(12345.12345, digits = 3)
[1] 12300

If you prefer significant digits to fixed digits then, the signif command might be useful:

> signif(1.12345, digits = 3)
[1] 1.12
> signif(12.12345, digits = 3)
[1] 12.1
> signif(12345.12345, digits = 3)
[1] 12300
小草泠泠 2024-09-20 22:49:23

检查函数 prettyNum, format

是否有试验零(例如 123.1240),使用 sprintf(x, fmt='%#.4g')

Check functions prettyNum, format

to have trialling zeros (123.1240 for example) use sprintf(x, fmt='%#.4g')

吃颗糖壮壮胆 2024-09-20 22:49:23

函数 formatC() 可用于将数字格式化为小数点后两位。即使结果值包含尾随零,该函数也会给出两位小数。

The function formatC() can be used to format a number to two decimal places. Two decimal places are given by this function even when the resulting values include trailing zeros.

提笔落墨 2024-09-20 22:49:23

我使用此变体强制打印 K 位小数:

# format numeric value to K decimal places
formatDecimal <- function(x, k) format(round(x, k), trim=T, nsmall=k)

I'm using this variant for force print K decimal places:

# format numeric value to K decimal places
formatDecimal <- function(x, k) format(round(x, k), trim=T, nsmall=k)
栖迟 2024-09-20 22:49:23

请注意,R 中的数字对象以双精度存储,这给你(大约)16 位小数精度的数字 - 其余的将是噪音。我承认上面显示的数字可能只是一个例子,但它有 22 位数字长。

Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.

总以为 2024-09-20 22:49:23

在我看来,就像

library(tutoR)
format(1.128347132904321674821, 2)

Per 一点 在线帮助

Looks to me like to would be something like

library(tutoR)
format(1.128347132904321674821, 2)

Per a little online help.

别念他 2024-09-20 22:49:23

如果您只想对数字或列表进行四舍五入,只需使用

round(data, 2)

然后,数据将四舍五入到小数点后两位。

if you just want to round a number or a list, simply use

round(data, 2)

Then, data will be round to 2 decimal place.

多孤肩上扛 2024-09-20 22:49:23
library(dplyr)
# round the numbers
df <- df %>%
  mutate(across(where(is.numeric), .fns = function(x) {format(round(x, 2), nsmall = 2)}))

在这里,我将所有数值更改为只有 2 位小数。如果需要更改为更多的小数位数

# round the numbers for k decimal places
df <- df %>%
  mutate(across(where(is.numeric), .fns = function(x) {format(round(x, k), nsmall = k)}))

将 k 替换为所需的小数位数

library(dplyr)
# round the numbers
df <- df %>%
  mutate(across(where(is.numeric), .fns = function(x) {format(round(x, 2), nsmall = 2)}))

Here I am changing all numeric values to have only 2 decimal places. If you need to change it to more decimal places

# round the numbers for k decimal places
df <- df %>%
  mutate(across(where(is.numeric), .fns = function(x) {format(round(x, k), nsmall = k)}))

Replace the k with the desired number of decimal places

兰花执着 2024-09-20 22:49:23

我编写了这个可以改进的函数,但看起来在极端情况下效果很好。例如,在 0.9995 的情况下,投票正确答案给出的结果是 1.00,这是不正确的。我在数字没有小数的情况下使用该解决方案。

round_correct <- function(x, digits, chars = TRUE) {
  if(grepl(x = x, pattern = "\\.")) {
    y <- as.character(x)
    pos <- grep(unlist(strsplit(x = y, split = "")), pattern = "\\.", value = FALSE)
    if(chars) {
      return(substr(x = x, start = 1, stop = pos + digits))
    }
    return(
      as.numeric(substr(x = x, start = 1, stop = pos + digits))
    )
  } else {
    return(
      format(round(x, 2), nsmall = 2)
    )
  }
}

例子:

round_correct(10.59648, digits = 2)
[1] "10.59"
round_correct(0.9995, digits = 2)
[1] "0.99"
round_correct(10, digits = 2)
[1] "10.00"

I wrote this function that could be improve but looks like works well in corner cases. For example, in the case of 0.9995 the vote correct answer gives us 1.00 which is incorrect. I use that solution in the case that the number has no decimals.

round_correct <- function(x, digits, chars = TRUE) {
  if(grepl(x = x, pattern = "\\.")) {
    y <- as.character(x)
    pos <- grep(unlist(strsplit(x = y, split = "")), pattern = "\\.", value = FALSE)
    if(chars) {
      return(substr(x = x, start = 1, stop = pos + digits))
    }
    return(
      as.numeric(substr(x = x, start = 1, stop = pos + digits))
    )
  } else {
    return(
      format(round(x, 2), nsmall = 2)
    )
  }
}

Example:

round_correct(10.59648, digits = 2)
[1] "10.59"
round_correct(0.9995, digits = 2)
[1] "0.99"
round_correct(10, digits = 2)
[1] "10.00"
稀香 2024-09-20 22:49:23

这是我从单位到百万的方法。
digits 参数让我调整有效值的最小数量(整数+小数)。您可以先调整内部的小数舍入。

number <-function(number){
  result <- if_else(
    abs(number) < 1000000,
    format(
      number, digits = 3,
      big.mark = ".",
      decimal.mark = ","
    ),
    paste0(
      format(
        number/1000000,
        digits = 3,
        drop0trailing = TRUE,
        big.mark = ".",
        decimal.mark = ","
      ),
      "MM"
    )
  )
  # result <- paste0("$", result)
  return(result)
}

here's my approach from units to millions.
digits parameter let me adjust the minimum number of significant values (integer + decimals). You could adjust decimal rounding inside first.

number <-function(number){
  result <- if_else(
    abs(number) < 1000000,
    format(
      number, digits = 3,
      big.mark = ".",
      decimal.mark = ","
    ),
    paste0(
      format(
        number/1000000,
        digits = 3,
        drop0trailing = TRUE,
        big.mark = ".",
        decimal.mark = ","
      ),
      "MM"
    )
  )
  # result <- paste0("
quot;, result)
  return(result)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文