r - knitr hook 可以分隔 000,但不会持续多年

标签 r knitr

我在 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 包起来在 commanocomma像:
 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/

相关文章:

r - 如何从R中其他列命名的列中选择数据

html - Rmarkdown knitr-HTML 中与 gridExtra 一致的数字大小

r - 功能注释未显示在 knitr (r studio) 中

r - 国际化 R knitr 图标题标签

替换字符串中的下标数字

r - 按一列匹配两个数据帧并从 R 中另一列中的匹配行中减去

r - R脚本中的here()问题

rstudio - 针织/ Markdown : how to render math equations in vignettes built by CRAN?

r - Caret 包中的 "random forest"错误

r - 直接来自数据的马尔可夫模型图(makovchain 或 deemod 包?)