Suppress output, keep pander and plot in R markdown - r

I have the following code in my Rmd file:
library(randomForestSRC)
library(ggRandomForests)
rf_all <- rfsrc(Y ~ ., data=df, block.size=1, ntree=100, importance=TRUE)
plot(gg_vimp(vimp.rfsrc(rf_all))) + theme(legend.position = "none")
rf_select <- var.select.rfsrc(rf_all)
pander(rf_select$varselect)
confmat <- confusionMatrix (rf_all$class.oob, data$Enddiagnosegruppe)
pander(confmat$table)
I'm trying to create an HTML report, but I cannot for the life of me figure out what chunk options to use such that:
The output of the rfsrc functions is suppressed.
All the plots appear.
The calls to pander yield properly formatted output.
I have tried pretty much all combinations of chunk options for message, warnings, error, as well as wrapping parts of my code in invisible(), capture.output(), as well as playing around with panderOptions('knitr.auto.asis', FALSE). Nothing seems to work, either the messages are not suppressed, pander tables look weird, empty section headers appear out of nowhere (I'm guessing "##" is inserted somewhere), no luck. I feel like I'm missing the forest for the trees here. Not to mention that this code is supposed to be wrapped in a loop that generates different formulae. Any suggestions on how to get this to work?

Using the following works:
rf_select <- var.select.rfsrc(rf_all, verbose=FALSE)
cat("\n")
pander(rf_select$varselect)
The problem is that var.select.rfsrc() uses cat() instead of message(), and somehow adding a newline is necessary since otherwise the first pander table is run together with the previous line in the markdown file.

Related

how to save the console in R to a file?

It's me again, quite the beginner at R but somehow fumbling my way through it for my thesis. I've run a bunch of regressions and made them into tables using Stargazer. Now I need to share all these results (the glm models/their summaries/the coefficients and confidence intervals and the stargazer tables ... basically everything in my console) with a friend of mine to discuss, but I figure there's got to be a more efficient way to do this than 1) screenshot-ing the hell out of my console or 2) copy and pasting the console and thus botching the formatting. Does anyone have any advice for this?
Some of my code (the rest is just variations on the same stuff) is below in case that's helpful!
Mod4 <- glm(`HC Annual Total` ~ `state population`
+ Year + `Trump Presidency`, data = thesis.data, family = poisson())
summary(Mod4)
#pulling the coefs out, then add exp for what reason I don't remember
exp(coef(Mod4))
#finding the confidence intervals
exp(confint(Mod4))
#Using stargazer to turn Mod4 into a cleaner table
library(stargazer)
stargazer(Mod4, type="text", dep.var.labels = c("Hate Crimes"),
covariate.labels = c("State Population", "Year", "Trump Presidency"),
out = "models.txt")
When you need it fast and without art, you could send console output to a simple text file using sink.
sink(file="./my_code.txt") ## open sink connection
timestamp()
(s <- summary(fit <- lm(mpg ~ hp, mtcars)))
cat('\n##', strrep('~', 77), '\n')
texreg::screenreg(fit, override.se=s$coe[,3], override.pvalues=s$coe[,4])
cat('\n# Note:
We could report t-values
instead of SEs\n')
cat('\n##', strrep('~', 77), '\n')
cat('\nCheers!\nJ')
sink() ## close it!
file.show("./my_code.txt") ## look at it
Note, that you can easily create a mess with unclosed sinks and no output is shown on the console. Try closeAllConnections() in this case or perhaps milder solutions. Also consider rmarkdown as suggested in comments.
savehistory() is your friend:
savehistory(file = "my-code.txt")
You can then edit the code at will.
Or, in RStudio, you can use the history pane and copy and paste relevant bits to a text file.
If a full rmarkdown document is overkill, you could try using knitr::spin() to compile your code.
Lastly:
In future, always write scripts.
Reproducibility is best thought of at the start of a project, not as an add-on at the end. It's much easier to run a carefully-written script at the console, than it is to turn your meandering console input into a useful script. A good workflow is to try a few things at the console, then once you know what you are doing, add a line to your script.
I think reprex is an intermediate solution between rmarkdown and sink. At first, make sure your R script can be executed without any errors. Then use the following code:
library(reprex)
r.file <- "path/to/Rscript/test.R" ## path to your R script file
reprex(input = r.file, outfile = NA)
There will be four files created in the directory of your R script file, i.e.
test_reprex.R
test_reprex.html
test_reprex.md
test_reprex.utf8.md
The html and md files contain codes in your original R script and their output. You can share with someone and they can see the output without running any codes.
The html file looks like:

inline Latex code inside knitr R block

I am looking for a way to put inline latex code into a R code chunk in Knitr.
Here is my example code from the knitr example site :
\documentclass{article}
\begin{document}
Example text outside R code here; we know the value of pi is \Sexpr{pi}.
<<my-label, echo=FALSE, eval=TRUE>>=
set.seed(1213) # for reproducibility
x = cumsum(rnorm(100))
m <- mean(x) # mean of x
print(m)
cat(m)
plot(x, type = 'l') # Brownian motion
#
\textit{Mean is :} \textbf{\Sexpr{m}}
\end{document}
For something simple like this is I could use result='asis' but for a more complicated piece of code, where you want to periodically write the result out to the document, (especially you have complex ggplot graphs), that solution does not work very well.
In the given example, I have 3 queries :
How would I use inline latex code for the output from line 8, in case I wanted to color, bold etc. that text.
Can one eliminate the grey box that appears when we use the cat or print command.
Can the numbering which appears with the print command, which is eliminated with the cat command be eliminated for the print command as well, since print has many variants in many packages for data frames data tables etc. and might be more commonly used to print a portion of data.
In summary, I am mainly looking for the inverse of line 12 in the code.
I have also unsuccessfully tried knit_print with printr, and asis_output, in lieu of print. Although I may have been incorrectly using them.
Thanks!

Function to get HTML syntax coloring in R

I was wondering if there is a way to have HTML output with syntax coloring of a line of code in R. It should do something like:
HTMLoutput <- HTMLsysntaxColoring("a <- paste('hello,', 'world')")
The output should be readable HTML code that shows the line with R syntax coloring.
Knit does something like this for a whole document, but I would like to have it for a single command line.
The reason why I am doing this is that I am developing a package to do profiling in R (it is in CRAN, GUIProfiler). It builds an HTML report that includes the profiled code shadowed for the places that take more time. Unfortunately, I used Nozzle.R1 instead of knitr to generate the report. Nozzle.R1 seems to be discontinued and is not able to display the code with syntax coloring. knitr is actively updated and does have syntax coloring.
Instead of rebuild the package from scratch using knitr (perhaps is what I will do in the future), I was trying "to patch it" using knitr to generate the syntax coloring and pasting it into the Nozzle.R1 package.
This ought to do it, though I'm curious as to what you're really actually looking for.
html_syntax_coloring <- function(r_code) {
require(knitr)
r_code <- paste0("```{r eval=FALSE}\n", paste0(r_code, collapse="\n"), "\n```")
tmp_in <- tempfile(fileext=".Rmd")
cat(r_code, file=tmp_in)
tmp_out <- tempfile(fileext=".html")
on.exit(unlink(tmp_out))
knit2html(tmp_in, tmp_out, quiet=TRUE)
paste0(readLines(tmp_out), collapse="\n")
}
html_syntax_coloring("a <- paste('hello,', 'world')")

Generating beanplots in a forloop with LaTeX

I am trying to automatically generate a number of beanplots with a forloop, and outputting them into a LaTeX document. Starting with a data frame (that successfully generates beanplots), I am using the code below. The intent is to output consecutive beanplots into the document. I am able to do this by writing a beanplot command for each desired plot (it works fine), but obviously this would be much nicer if I could do it with a forloop. However, when I try to use a forloop, instead of outputting say 9 plots, it only outputs the last plot. Any ideas on why this is? I tried using fig.keep='all' and plot.new(), neither helped. Compiling with Sweave. Thanks!
<<beanplots,fig.keep='all'>>=
#fig.keep='all' <- this did not help
suppressPackageStartupMessages(require(beanplot))
for (i in length(unique(Data[['Days']]))){
# plot.new() ## this did not help either
beanplot(Readings~FactorLevels,
data=subset(x=Data, subset=(Data[['Days']]==i)),
main=paste("Day",i,sep=" "),
cex.axis=0.7)
}
#
beanplot works with the Lattice graphics library. As such, it does not automatically produce plots when running non-interactively. You must explicitly call print() on the object returned by the call to produce a plot. Try
<<beanplots,fig.keep='all'>>=
#fig.keep='all' <- this did not help
suppressPackageStartupMessages(require(beanplot))
for (i in unique(Data[['Days']])){
# plot.new() ## this did not help either
print(beanplot(Readings~FactorLevels,
data=subset(x=Data, subset=(Data[['Days']]==i)),
main=paste("Day",i,sep=" "),
cex.axis=0.7))
}
#

Can I suppress the arrow (">") in the R/S output in Sweave?

whenever I run some R code with Sweave, it displays the terminal arrows (">") in the document. This is fine for session inputs, but sometimes I'd like to include custom functions. When arrows show up in the document, it is more difficult to copy and paste important snippets of code. Is there a quick way to do this?
I know I can run the code while suppressing the output all together, and then copy that code into a \Verbatim, but that requires extra typing.
Thanks
dumbo <- function(x)
2*x
instead of
> dumbo <- function(x)
> 2*x
Just add this to the top of the first chunk:
options(prompt=" ",continue=" ")
You can get back any moment with:
options(prompt="> ",continue="+ ")
options(prompt=" ")
You can set it back at the end.
options(prompt="> ")
This is off by default in knitr, the "next generation Sweave". Other nice features include syntax coloring and PGF integration.
Sweave code of average complexity needs only minor if any adaptions to run with knitr.

Resources