在 knitr 上设置全局千位分隔符 [英] Set global thousand separator on knitr

查看:11

问题描述

我希望我的 knitr 报告中的所有数字都默认设置为这样的格式:

format(num, digits = 2, big.mark = " ", decimal.mark = ",")

默认位数为 2,小数点为逗号很容易,我只需要在我的第一个 R 块中设置 options(digits = 2, OutDec = ",") .但是,我看不到如何以这种格式将千位分隔符设置为 " " (或其他任何内容).我也尝试过调整 opts_chunk,但无法正常工作.

当然,我试图避免在每个输出中插入 format(),内联或其他.毕竟,更智能的格式是促使我从 Sweave 转向 knitr 的一件事.

如何在 knitr 上设置默认的千位分隔符?

解决方案

正如 Frank 所说,设置如下所示的 knitr hook 可以解决问题:

knit_hooks$set(inline = function(x) {prettyNum(x, big.mark=" ")})

事实证明,knitr hooks 是调整 knitr 上 R 块输出的好方法.http://yihui.name/knitr/hooks 真的值得一看.p>

来源:https://groups.google.com/论坛/#!msg/knitr/CnFwvk1Qn1E/WY-Xhf7Ph3AJ

I want all the numbers on my knitr report to be formatted as such by default:

format(num, digits = 2, big.mark = " ", decimal.mark = ",")

Defaulting the number of digits to 2 and the decimal mark to comma is easy, I just need to set options(digits = 2, OutDec = ",") in my first R chunk. However, I don't see how I can set the thousand separator to " " (or anything else, for that matter) in that format. I've also tried tweaking opts_chunk, but can't get it to work.

Of course, I'm trying to avoid having to insert format() inside every output, inline or otherwise. More intelligent formatting is one thing that drove me towards knitr from Sweave, after all.

How can I set default thousand separator marks on knitr?

解决方案

As Frank noted, setting a knitr hook such as the following solves the problem:

knit_hooks$set(inline = function(x) {
  prettyNum(x, big.mark=" ")
})

It turns out knitr hooks are a great way to tweak the output of R chunks on knitr. It's really worth it to take a look at http://yihui.name/knitr/hooks.

Source: https://groups.google.com/forum/#!msg/knitr/CnFwvk1Qn1E/WY-Xhf7Ph3AJ

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