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.
Related
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:
I have an RMarkdown document where I use data.tree and DiagrammeR to generate models. I then display these using a set-up similar to the one used in How to include DiagrammeR/mermaid flowchart in a Rmarkdown file
For example:
```{r fig.cap="Structureel model bij enkelvoudige regressie.", fig.with=4, fig.height=1}
drawStructuralModel <- function(covariates, criterion) {
### Create tree
res <- Node$new(criterion);
for (covariate in covariates) {
res$AddChild(covariate);
}
### Set display settings
SetEdgeStyle(res, dir='back');
res <- ToDiagrammeRGraph(res, direction = "descend");
res <- add_global_graph_attrs(res, "layout", "dot", "graph");
res <- add_global_graph_attrs(res, "rankdir", "RL", "graph");
### Draw and return tree
render_graph(res);
}
drawStructuralModel("X", "Y");
```
So far so good. The caption text is added, which is what you'd expect.
Except :-)
Above, in the 'setup' knitr chunk, I used setFigCapNumbering from userfriendlyscience (see https://github.com/Matherion/userfriendlyscience/blob/master/R/setFigCapNumbering.R). This function uses knit_hooks$set to set a hook for plots, so that the captions are automatically numbered.
But this numbering isn't applied to the DiagrammeR output.
I guess that makes sense, since it's not actually a plot, rather an HTML widget or some SVG or so. I would still like it to be numbered as a figure, though.
But how do I find out which hook knitr invokes when DiagrammeR output is generated?
I could always resort to using the more generic 'automatic caption' function setCaptionNumbering (https://github.com/Matherion/userfriendlyscience/blob/master/R/setCaptionNumbering.R), and tell it to use the same counter option as the figure caption thingy uses. That would sidestep the issue, but I'd prefer to modify the appropriate knitr hook.
And since this problem (figuring out which hook knitr uses for output produced by a given function) probably occurs more often, I thought it would be worth opening an SA question.
Does anybody know how you can find this out?
knitr calls knit_print on the output produced by a given chunk. This then calls the appropriate method based on the class of the output. You can find out what methods are available by running methods("knit_print"), then see if any of those match the class of the output from DiagrammeR.
Looking at your example, I'm guessing the class of your output is "DiagrammeR" "htmlwidget", so knitr is calling knit_print.htmlwidget.
Digging into that source code, it calls htmltools::knit_print.html, which wraps the tags and then outputs asis. So to answer your question, it uses the default hooks for asis output in whatever output format you're using.
I want to add hashtag # sign before many lines in r. How can I do it using a shortcut key?
R Studio: Highlight the text and use CTRL+SHIFT+C to comment multiple lines.
I know this is slightly different to the question asked but after multiple failed searches on stackoverflow for a solution to my question, all which ended up on this page, I thought I would add this for anyone in a similar situation. I was looking for a quick way (purely for aesthetic commenting reasons) to add a line of #### across a R script, rather than holding down the # button, I came across the bannerCommenter package which I think is really useful. It also has other formats.
library(bannerCommenter)
#run the following command which saves the comment to clipboard
#then just paste on next line of script
banner("Section 1:", "Data input and initialization", emph = TRUE)
###########################################################################
###########################################################################
### ###
### SECTION 1: ###
### DATA INPUT AND INITIALIZATION ###
### ###
###########################################################################
###########################################################################
rather than multiple "#", i prefer to use ' (apostrof) between lines to disable it. for example:
'dim(train);dim(test)
names(train)
names(test)
str(train)
str(test)'
in R console, 5 lines above will return:
> 'dim(train);dim(test)
+ names(train)
+ names(test)
+ str(train)
+ str(test)'
[1] "dim(train);dim(test)\nnames(train)\nnames(test)\nstr(train)\nstr(test)"
>
There is a simple way of doing this!!!
If you are using a mouse press the scroll button (don't scroll it) over the edge of the starting of line. Many signs like "|" would be made. Now just press 'shift + #' to comment multiple lines or even a paragraph in python.
For MAC (R Studio): Highlight the text and use COMMAND+SHIFT+C to comment multiple lines. The same is for removing comment.
In base R (on a Mac), highlight multiple rows and use: command + '.
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')")
I'm very new to sweave and I feel this will be an easy question, but I'm struggling to solve it myself (googling omit ">" Sweave doesn't really work because I can't search for ">"!).
I'm including a short script into my document:
<<echo=true, results=hide, eval=false>>=
# This is a simple script.
print('Hello World!\n')
#
I basically want the script to appear verbatim in the document, using whatever Sweave's "code" environment is. I don't want to evaluate it - it's just there to demonstrate how one might write a script utilising the functions in the package this document is for.
However, this produces the following in the output document:
> # This is a simple script
> print('Hello World!\n')
Is there some way to omit the > ? Is this the right way to put a script into a Sweave document, or is there some other environment that is meant to be used? (I can use a \begin{verbatim}, but it seemed to me that I should use Sweave commands if possible for code chunks).
I just want the output to be
# This is a simple script.
print('Hello World!\n')
You can try changing the prompt and continue options,
which define the > and + characters.
options(continue=" ", prompt=" ")
I like Vincent's first idea using knitr.
install.packages("knitr")
library(knitr)
Here's a sample Rnw.
\documentclass[a4paper]{article}
%\usepackage{Sweave}
\title{Test case}
\author{romunov}
\begin{document}
\maketitle
<<eval = FALSE, echo = TRUE>>=
# This is a simple script.
print('Hello World!\n')
#
\end{document}
And then
knit("coffee.Rnw")
Convert your .tex file into something pretty, and you get