设置输出中显示的小数位数

Luc*_*caS 6 r knitr r-markdown

我想要更多地使用 R markdown 来执行分析和生成输出。也许我错过了一些简单的东西,但我只想能够设置小数位数以显示 2 或 3 位数字,具体取决于输出(例如 t 统计量与 p 值)。

我以前使用过r options(digits=2),它一直有效,直到您要包含的最后一个数字为 0。我已经使用 sprintf 函数解决了这个问题,但必须为每个数字指定。

有没有办法设置“全局”sprintf 选项,以便对于后面的所有数字,显示相同的小数位数?

谢谢你,

保罗

RLe*_*sur 8

使用内联钩子定义内联代码输出的格式是可行的knitr(钩子是 的隐藏宝石knitr)。

示例 #1
通过此文件,无需在所有内联代码中Rmd使用即可控制小数位数:sprintf()

---
title: "Use an inline hook"
---
```{r setup, include=FALSE}
# Register an inline hook:
knitr::knit_hooks$set(inline = function(x) {
  x <- sprintf("%1.2f", x)
  paste(x, collapse = ", ")
})
```
Now, get 3.14 with just writing `r pi`.
Run Code Online (Sandbox Code Playgroud)

示例 #2
想要更改报告某些部分的内联输出格式?
Rmd文件的作用是:

---
title: "Use a closure and an inline hook"
---
```{r setup, include=FALSE}
# Register an inline hook
knitr::knit_hooks$set(inline = function(x) {
  paste(custom_print(x), collapse = ", ")
})
# Define a function factory (from @eipi10 answer)
op <- function(d = 2) {
  function(x) sprintf(paste0("%1.", d, "f"), x)
}
# Use a closure
custom_print <- op()
```
Now, get 3.14 with `r pi`...
```{r three-decimals, include=FALSE}
custom_print <- op(d = 3)
```
...and now 3.142 with `r pi`.
```{r more-decimals, include=FALSE}
custom_print <- op(d = 10)
```
Finally, get 3.1415926536 with `r pi`.
Run Code Online (Sandbox Code Playgroud)

示例 #3
想要显示 t 统计量和 p 值的不同格式?
可以使用 S3 对象和内联钩子,如以下Rmd文件所示:

---
title: "Use S3 methods and an inline hook"
---
```{r setup, include=FALSE}
# Register an inline hook
knitr::knit_hooks$set(inline = function(x) {
  paste(custom_print(x), collapse = ", ")
})
# Define a generic
custom_print <- function(x, ...) {
  UseMethod("custom_print", x)
}
# Define a method for p-values
custom_print.p.value <- function(x, ...) paste(sprintf("%1.2f", x), collapse = ", ")
# Define a method for t-statistics
custom_print.t.stat <- function(x, ...) paste(sprintf("%1.1f", x), collapse = ", ")
```
Estimate models...
```{r fake-results, include=FALSE}
t <- c(2.581, -1.897)
class(t) <- "t.stat"
p <- c(0.025, 0.745)
class(p) <- "p.value"
```
Want to show T-stats: `r t` (get 2.6, -1.9).  
And p-values: `r p` (get 0.03, 0.74).
Run Code Online (Sandbox Code Playgroud)

谁说knitr这是一个很棒的包?


eip*_*i10 5

我不知道如何设置全局选项(尽管可能有)。但是您可以编写一个方便的输出函数来减少输入量。例如,将此函数放在文档的开头:

op = function(x, d=2) sprintf(paste0("%1.",d,"f"), x) 
Run Code Online (Sandbox Code Playgroud)

然后,稍后在文档中,当您想要输出数字时,您可以执行以下操作:

op(mtcars$mpg)
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要 3 位数字而不是默认的 2 位数字,您可以执行以下操作:

op(mtcars$mpg, 3)
Run Code Online (Sandbox Code Playgroud)