7

我正在开发我的第一个 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 笔记本吗?

编辑:

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

4

1 回答 1

1

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

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 时,输出如下所示,表明两种技术产生相同的结果。

在此处输入图像描述

问候,

于 2017-11-24T21:12:20.617 回答