Skip to content

Instantly share code, notes, and snippets.

@dantonnoriega
Created March 27, 2016 15:40
Show Gist options
  • Save dantonnoriega/a3f14f83b1c9ab55ce2d to your computer and use it in GitHub Desktop.
Save dantonnoriega/a3f14f83b1c9ab55ce2d to your computer and use it in GitHub Desktop.
Some functions which take xtable objects and print as kable objects, keeping track, extracting the caption automatically, and then using pandoc-tablenos for referencing.
assignCount <- function(obj, kind, new=FALSE) {
# fromi https://rmflight.github.io/posts/2012/10/papersinRmd.html
incCount <- function(inObj, useName) {
nObj <- length(inObj)
useNum <- max(inObj) + 1
inObj <- c(inObj, useNum)
names(inObj)[nObj + 1] <- useName
inObj
}
kindCount <- paste0(kind, 'Count') # create counting object ('tblCount' or 'figCount')
kind1 <- paste0(kind,'1') # initializing value ('tbl1' or 'fig1')
if(!exists(kindCount) | new) {
kind0 <- 1 # create first value of counter
names(kind0) <- kind1 # assign correct kind name
assign(kindCount, kind0, envir = .GlobalEnv) # create counter if doesn't exists
assign(kind1, obj, envir = .GlobalEnv) # add first table
rm('kind0')
} else {
kindNext <- paste0(kind, length(get(kindCount)) + 1)
assign(kindNext, obj, envir = .GlobalEnv)
assign(kindCount, incCount(get(kindCount), kindNext), envir = .GlobalEnv) # update counter
}
}
## tabular2xtable
tabular2xtable <- function(x, caption=NULL){
cat("\\begin{table}[ht]\n")
cat("\\centering\n")
latex(x)
if(!is.null(caption)) cat("\\caption{",caption,"}\n", sep="")
cat("\\end{table}\n")
}
## Print Table
printTable <- function(tbl, label=NULL, new=FALSE) {
stopifnot(!is.null(label))
if(!is.null(label)) stopifnot(inherits(label, 'character'))
assignCount(tbl, kind='table', new=new)
num <- length(tableCount)
tableCount[num] <- label
cap <- paste0(attr(tbl, "caption"), " {#tbl:", label,"}")
kable(tbl, caption=cap)
}
## reference Table
refTable <- function(label) {
I(paste0("@tbl:", label))
}
## Print Fig
printFig <- function(fig, label=NULL, new=FALSE) {
stopifnot(!is.null(label))
if(!is.null(label)) stopifnot(inherits(label, 'character'))
assignCount(fig, kind='table', new=new)
num <- length(tableCount)
tableCount[num] <- label
cap <- paste0(attr(fig, "caption"), " {#fig:", label,"}")
kable(fig, caption=cap)
}
## reference Fig
refFig <- function(label) {
I(paste0("@fig:", label))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment