Wednesday 15 May 2013

r - knitr hook to separate 000's, but not for years -



r - knitr hook to separate 000's, but not for years -

i define hook @ top of rnw separate '000s commas:

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

however, there numbers don't want format this, such years. there improve way write hook, or way override hook when print \sexpr{nocomma} in illustration below?

\documentclass{article} \begin{document} <<setup>>= library(knitr) options(scipen=999) # turn off scientific notation 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" @ hook separate \sexpr{wantcomma} , \sexpr{nocomma}, don't want separate years. \end{document}

output:

the hook separate 6,170 , september 1, 2,014, don’t want separate years.

if things don't want comma-separated strings have years in, use:

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

that works calendar string. suppose want print year number on own? well, how using above hook , converting character:

what \sexpr{2014}? % gets commad \sexpr{as.character(2014)}? % not commad

or perchance (untested):

what \sexpr{paste(2014)}? % not commad

which converts scalar character , saves bit of typing. we're not playing code golf game here though...

alternatively class-based method:

comma <- function(x){structure(x,class="comma")} nocomma <- function(x){structure(x,class="nocomma")} options(scipen=999) # turn off scientific notation 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 alter here not clash function

then wrap sexpr in either comma or nocomma like:

hook separate \sexpr{comma(wantcomma)} , \sexpr{nocomma(nocomma1)}, don't want separate years.

if want default commaify alter line commented "# default" utilize prettynum. although i'm thinking i've overcomplicated , comma , nocomma functions compute string format , wouldn't need hook @ all.

without knowing cases don't think can write function infers comma-sep scheme - illustration have know "1342 cases in 2013" needs first number commad , not second...

r knitr

No comments:

Post a Comment