Skip to content

Instantly share code, notes, and snippets.

@ramnathv
Created March 16, 2012 16:08
Show Gist options
  • Save ramnathv/2050761 to your computer and use it in GitHub Desktop.
Save ramnathv/2050761 to your computer and use it in GitHub Desktop.
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
Copy link

That's beautiful, thanks for sharing!

@yihui
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