Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R markdown – Can I suppress leading linefeeds/whitespace in output from basic code chunk functions?

High school stats teacher here — I’m creating R markdown summaries of the answers/approaches to various labs and assignments where I demonstrate the R code necessary to support the necessary queries/analyses.

It’s working great, but I have one minor formatting challenge I haven’t been able to sort out. In my markdown files, I intermingle commentary with the code, and so have formatted textual intros/outros to various code blocks. In some cases, I simply want to show the function call followed by the output, and some functions produce a bit of leading whitespace that if possible, I’d like to remove/suppress. Here is an example:

Example A - table function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As I say, it’s a minor quibble, but the leading whitespace is a bit ungainly with the shorter function responses, and if it’s possible to remove it with a little heretofore undiscovered setting of option(s) or code, I’d love to be able to deal with it. Thanks in advance for your help.

Details of my world: using R Studio on Posit, doing R markdown with knitr and outputting to HTML.

>Solution :

This is the way table() results are printed when you don’t name the arguments. If you named it you’d see something different, e.g.
table(species = animal$type) would print as

species
cat dog
182 291

knitr does provide a few ways to manipulate output. In this case, the easiest might be to provide a knit_print.table method, e.g. just define the function

knit_print.table <- function(x, ...) {
  lines <- capture.output(print(x, ...))
  cat(lines[lines != ""], sep = "\n")
}

and knitr will drop blank lines when it prints.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading