Last active
December 20, 2015 21:28
-
-
Save brian-bot/6197439 to your computer and use it in GitHub Desktop.
A function to render Synapse-specific markdown for table rendering
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##### | |
## AUTHOR: BRIAN M. BOT | |
## ORGANIZATION: SAGE BIONETWORKS | |
## | |
## FUNCTION TO RENDER SYNAPSE-SPECIFIC MARKDOWN FOR TABLE RENDERING | |
##### | |
## PARAMETERS: | |
## x: an R object of class data.frame, matrix, or table | |
## row.names (=TRUE): whether or not to include row names in the table (if available) | |
## col.names (=TRUE): whether or not to include column names in the table (if available) | |
##### | |
## VALUE: | |
## NULL - uses 'cat' to output Synapse-specific markdown for table rendering | |
##### | |
synTable <- function(x, row.names=TRUE, col.names=TRUE){ | |
## HANDLE DATA FRAMES (IN A HACKY WAY) | |
if( is.data.frame(x) ){ | |
xtmp <- as.matrix(x) | |
rownames(xtmp) <- rownames(x) | |
x <- xtmp | |
} | |
## SET FENCE FOR SYNAPSE TABLE | |
startFence <- '{| class="border text-align-center"' | |
endFence <- "|}\n" | |
## NOW HANDLE ALL MATRICES | |
if( is.matrix(x) ){ | |
if( row.names ){ | |
tab <- apply(cbind(rownames(x), x), 1, paste, collapse = " | ") | |
if( col.names ){ ## ROWNAMES AND COLNAMES | |
colLabs <- paste(c(" ", colnames(x)), collapse=" | ") | |
cat(paste(c(startFence, colLabs, tab, endFence), collapse = '\n')) | |
} else{ ## ROWNAMES ONLY | |
cat(paste(c(startFence, tab, endFence), collapse = '\n')) | |
} | |
} else{ | |
tab <- apply(x, 1, paste, collapse=" | ") | |
if( col.names ){ ## COLNAMES ONLY | |
colLabs <- paste(colnames(x), collapse=" | ") | |
cat(paste(c(startFence, colLabs, tab, endFence), collapse = '\n')) | |
} else{ ## NEITHER | |
cat(paste(c(startFence, tab, endFence), collapse = '\n')) | |
} | |
} | |
} | |
## CASE FOR SINGLE TABLE - E.G. table(rep(1:4, 5)) | |
if( !is.matrix(x) & is.table(x) & length(dim(x)) == 1L ){ | |
tab <- paste(x, collapse=" | ") | |
if( col.names ){ | |
colLabs <- paste(names(x), collapse=" | ") | |
cat(paste(c(startFence, colLabs, tab, endFence), collapse = '\n')) | |
} else{ | |
cat(paste(c(startFence, tab, endFence), collapse = '\n')) | |
} | |
} | |
return(invisible(NULL)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment