我在 rnw
的顶部定义了一个钩子(Hook)用逗号分隔 '000:
knit_hooks$set(inline = function(x) {
prettyNum(x, big.mark=",")
})
但是,有些数字我不想这样格式化,例如年份。有没有更好的方法来编写钩子(Hook),或者当我打印
\Sexpr{nocomma}
时覆盖钩子(Hook)的方法?在下面的例子中?\documentclass{article}
\begin{document}
<<setup>>=
library(knitr)
options(scipen=999) # turn off scientific notation for numbers
opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE)
knit_hooks$set(inline = function(x) {
prettyNum(x, big.mark=",")
})
wantcomma <- 1234*5
nocomma <- "September 1, 2014"
@
The hook will separate \Sexpr{wantcomma} and \Sexpr{nocomma}, but I don't want to separate years.
\end{document}
输出:
The hook will separate 6,170 and September 1, 2,014, but I don’t want to separate years.
最佳答案
如果您不希望逗号分隔的唯一内容是具有多年历史的字符串,请使用:
knit_hooks$set(inline = function(x) {
if(is.numeric(x)){
return(prettyNum(x, big.mark=","))
}else{
return(x)
}
})
这适用于您的日历字符串。但是假设您只想自己打印一个年份数字?那么,如何使用上面的钩子(Hook)并转换为字符:
What about \Sexpr{2014}? % gets commad
What about \Sexpr{as.character(2014)}? % not commad
或可能(未经测试):
What about \Sexpr{paste(2014)}? % not commad
它将标量转换为字符并节省了一些输入。不过,我们不是在这里打代码高尔夫……
或者基于类的方法:
comma <- function(x){structure(x,class="comma")}
nocomma <- function(x){structure(x,class="nocomma")}
options(scipen=999) # turn off scientific notation for numbers
opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE)
knit_hooks$set(inline = function(x) {
if(inherits(x,"comma")) return(prettyNum(x, big.mark=","))
if(inherits(x,"nocomma")) return(x)
return(x) # default
})
wantcomma <- 1234*5
nocomma1 <- "September 1, 2014" # note name change here to not clash with function
然后把你的
Sexpr
包起来在 comma
或 nocomma
像: The hook will separate \Sexpr{comma(wantcomma)} and \Sexpr{nocomma(nocomma1)}, but I don't want to separate years.
如果您希望默认使用逗号,则将注释为“# default”的行更改为使用
prettyNum
.虽然我在想我已经把这个和 comma
复杂化了。和 nocomma
函数可以自己计算字符串格式,然后你根本不需要钩子(Hook)。在不确切知道您的案例的情况下,我认为我们不能编写一个推断逗号分隔方案的函数 - 例如,它必须知道“2013 年的 1342 个案例”需要它的第一个数字逗号,而不是第二个......
关于r - knitr hook 可以分隔 000,但不会持续多年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26382512/