R笔记本:opts_chunk没有效果

时间:2016-12-16 14:36:12

标签: r rstudio r-markdown rnotebook

我正在使用我的第一台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对数字的输出格式也没有影响。

1 个答案:

答案 0 :(得分: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文件中并编织时,输出如下,表明两种技术都产生相同的结果。

enter image description here

的问候,

Len