Knitr hook to split 000, but not for years

I define a hook at the top of my rnw to separate '000 with commas:

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

However, there are some numbers that I do not want to format, for example, years. Is there a better way to write a hook or a way to override a hook when I type \Sexpr{nocomma} in the example below?

 \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} 

Conclusion:

The hook will separate 6 170 and September 1, 2014, but I do not want to separate the years.

+5
source share
1 answer

If the only things you don't want to separate with commas are strings that have years in them, use:

  knit_hooks$set(inline = function(x) { if(is.numeric(x)){ return(prettyNum(x, big.mark=",")) }else{ return(x) } }) 

This works for your calendar line. But suppose you just want to print the year number yourself? Well, what about using the above hook and converting to a character:

 What about \Sexpr{2014}? % gets commad What about \Sexpr{as.character(2014)}? % not commad 

or possibly (unverified):

 What about \Sexpr{paste(2014)}? % not commad 

which converts a scalar to a character and stores the input bit. We don't play golf here though ...

Alternative class based method:

  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 

Then just wrap Sexpr in comma or nocomma , for example:

  The hook will separate \Sexpr{comma(wantcomma)} and \Sexpr{nocomma(nocomma1)}, but I don't want to separate years. 

If you want the comma to be the default, change the line marked with "# default" to use prettyNum . Although I think I complicated it too much, and the comma and nocomma could just compute their own string format, and then you wouldn't need a hook at all.

Not knowing exactly your cases, I don’t think we can write a function that introduces the sep comma scheme, for example, it should know that β€œ1342 cases in 2013” ​​needs its first commad number, and not the second .. .

+6
source

Source: https://habr.com/ru/post/1204733/


All Articles