R笔记本:opts_chunk不起作用 [英] R notebook: opts_chunk has no effect

查看:266
本文介绍了R笔记本:opts_chunk不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究我的第一台R笔记本,除了一个问题之外,它运行良好. 我想成为

I'm working on my first R notebook which works pretty well, except for one issue. I'd like to be the numbers that I output inline with

`r realbignumber`

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

to have commas as separator and max 2 decimal points: 123,456,789.12

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

In order to achieve this, I added a chunk at the beginning of my document, which contains...

```{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)
```

对科学数字的压制就像是一种魅力,因此该代码块一定会被执行.但是,数字内联输出的格式不起作用.

The suppression of scientific numbers works like a charm, so the chunk is definitely executed. However, formatting of the inline output of numbers does not work.

有什么想法可能会这样吗? 这些设置通常不适用于R笔记本电脑吗?

Any ideas why that could be? Do these kinds of settings generally not work with R notebooks?

建议的解决方案在此也不会影响数字.

The solution suggested here also has no effect on the output format of numbers.

推荐答案

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

Here is an example illustrating two ways to print a large number in an R Markdown document. First, code to use the prettyNum() function in an inline R chunk.

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=",")`.

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

The alternative of using chunk options works as follows.

 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文件中并进行编织时,输出如下所示,表明这两种技术均产生相同的结果.

When both chunks of code are embedded in an Rmd file and knit, the output is as follows, showing that both techniques produce the same result.

致谢

Len

这篇关于R笔记本:opts_chunk不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆