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:
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.
