Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GFM Table with knitr + ascii

Here is how you can make a table in GFM format using knitr + ascii

render_gfm()
gfm_table <- function(x, ...) {
    require(ascii)
    y <- capture.output(print(ascii(x, ...), type = "org"))
    # substitute + with | for table markup
    # TODO: modify regex so that only + signs in markup,
    #   like -+- are substituted
    y <- gsub("[+]", "|", y)
    return(writeLines(y))
}
x <- head(mtcars[, 1:3])
gfm_table(x)
mpg cyl disp
Mazda RX4 21.00 6.00 160.00
Mazda RX4 Wag 21.00 6.00 160.00
Datsun 710 22.80 4.00 108.00
Hornet 4 Drive 21.40 6.00 258.00
Hornet Sportabout 18.70 8.00 360.00
Valiant 18.10 6.00 225.00

Here is how you can make a table in GFM format using knitr + ascii

<!-- begin.rcode 
render_gfm()
gfm_table <- function(x, ...){
  require(ascii)
  y <- capture.output(print(ascii(x, ...), type = 'org'))
  # substitute + with | for table markup
  # TODO: modify regex so that only + signs in markup, like -+- are substituted
  y <- gsub('[+]', '|', y)
  return(writeLines(y))
}
end.rcode -->
<!-- begin.rcode results = 'asis'
x <- head(mtcars[,1:3])
gfm_table(x)
end.rcode -->
@cboettig

This comment has been minimized.

Copy link

cboettig commented Mar 16, 2012

That's beautiful, thanks for sharing!

@yihui

This comment has been minimized.

Copy link

yihui commented Mar 16, 2012

probably we can only replace + in the second line... or restrict the replacement to -+- (with -|-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.