How to avoid using round() in every \Sexpr{}?

丶灬走出姿态 提交于 2019-12-28 08:10:19

问题


Is there a way to avoid the function round() when using Sweave/knitr? It's really annoying to write round(,2) in every \Sexpr{}. I would like to have two decimal places through the whole document.

Thanks for your help
Macs


回答1:


If you have read the motivation of the knitr package, you probably know I'm the person who hates round() inside \Sexpr{} most. I suggested this to R core long time ago for Sweave but it was ignored, so I started my own package.

Although the answer by Josh O'Brien is absolutely correct, I should say you really only need options(digits = 2) with knitr, and there is no need to reset the default inline hook because the default hook respects this option.




回答2:


In knitr, the inline hook can be used to process the output of \Sexpr{} statements. So, if you want to print just 2 digits after the decimal for inline code (while leaving the overall digits option alone) you can do so like this:

## First have a look at the default inline hook function
knit_hooks$get("inline")

## Then customize it to your own liking
inline_hook <- function(x) {
    if(is.numeric(x)) x <- round(x, 2)
    paste(as.character(x), collapse=", ")
}
knit_hooks$set(inline = inline_hook)



回答3:


First, you perhaps want to use formatC instead of round to get two digits even when they are zero. There's not a great way to do this in Sweave; the best option is probably simply to make a new function with a short name that does the formatting you want; something like

p <- function(x) {formatC(x, format="f", digits=2)}

That at least saves a little bit of typing:

The answer is $\Sexpr{p(x)}$.

Unfortunately, without mucking about with a new Sweave driver, I don't think there's anything else to do (perhaps this is another reason to try knitr, which seems to be gaining ground fast). Sweave is doing this on what's inside your Sexpr statement, and then replacing the Sexpr call with the result.

as.character(eval(parse(text = cmd), envir = .GlobalEnv))

However, you can't just write a new version of as.character; aside from the issue that it might change behavior in other unexpected ways, because of the namespacing, it always calls the version in base even if there's another version in the global environment.



来源:https://stackoverflow.com/questions/11062497/how-to-avoid-using-round-in-every-sexpr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!