【问题标题】:R notebook: opts_chunk has no effectR笔记本:opts_chunk没有效果
【发布时间】:2017-05-02 09:14:21
【问题描述】:

我正在开发我的第一个 R 笔记本,它运行良好,除了一个问题。 我想成为与

内联输出的数字
`r realbignumber`

以逗号作为分隔符,最多 2 个小数点:123,456,789.12

为了实现这一点,我在文档的开头添加了一个块,其中包含...

```{r setup}
knitr::opts_chunk$set(echo = FALSE, warning=FALSE, cache = TRUE, message = FALSE)
knitr::opts_chunk$set(inline = function(x){if(!is.numeric(x)){x}else{prettyNum(round(x,1), big.mark = ",")}})
options(scipen=999)
```

科学数字的抑制就像一个魅力,所以这个块肯定会被执行。但是,数字的内联输出的格式不起作用。

任何想法为什么会这样? 这些设置通常不适用于 R 笔记本吗?

编辑:

here建议的解决方案也对数字的输出格式没有影响。

【问题讨论】:

  • 我实际上找不到用于格式化内联结果的 inline 块选项。你能指出讨论过的文档吗?
  • 我删除了我的答案,因为我发现了这个:stackoverflow.com/a/18967590/3022126
  • 我尝试了您链接到的问题底部提到的钩子 (knitr::knit_hooks$set(inline = function(x) { if(!is.numeric(x)){ x } else{ prettyNum(round(x,2), big.mark=",") } })) 但它也不影响输出。
  • 是否有可能删除“标记为重复”? @皮埃尔?
  • 我重新打开了这个问题。

标签: r rstudio r-markdown rnotebook


【解决方案1】:

这是一个示例,说明了在 R Markdown 文档中打印大数字的两种方法。首先,在内联 R 块中使用 prettyNum() 函数的代码。

Sample document where we test printing a large number. First set the number in an R chunk. 
```{r initializeData}
theNum <- 1234567891011.03
options(scipen=999,digits=16)
```

The R code we'll use to format the number is: `prettyNum(theNum,width=23,big.mark=",")`.

Next, print the large number. `r prettyNum(theNum,width=23,big.mark=",")`.

使用块选项的替代方法如下。

 Now, try an alternative using knitr chunks.

 ```{r prettyNumHook }
 knitr::knit_hooks$set(inline = function(x) { if(!is.numeric(x)){ x }else{ prettyNum(x, big.mark=",",width=23) } })
 ```
 Next, print the large number by simply referencing the number in an inline chunk as `theNum`: `r theNum`. 

当两个代码块都嵌入到 Rmd 文件中并 knit 时,输出如下所示,表明两种技术产生相同的结果。

问候,

镜头

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    相关资源
    最近更新 更多