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
Related
I'm experimenting with Rmd Notebooks, and I'm stuck on something that seems like it should be possible but I cannot figure out a solution at all.
Basically, I would like a functional way to run selected Rmd chunks without compiling with knitr. So I don't think using dependent chunks, caching, etc. will work here.
Here is an example notebook:
Example_Notebook.Rmd
---
title: "Example_Notebook"
output: html_notebook
---
```{r Chunk_1 , include=T}
print(1+2)
Var1 <- 'Variable From Chunk 1'
```
```{r Chunk_2 , include=T}
Var2 <- 'Variable From Chunk 2'
```
```{r Chunk_3 , include=T}
print(Var1)
Var3 <- 'Variable From Chunk 3'
print(Var3)
```
Let's say I wanted to run Chunk 1 & Chunk 3. To do it manually, I could use Ctrl+Shift+Enter while my cursor is in Chunk_1, and then Ctrl+Shift+Enter again while my cursor is in Chunk_3. This would skip Chunk_2 while still getting output for 1 & 3.
I'm looking for a way to do this in a single command/function. This would be similar to the button in RStudio "Run All Chunks Above" except obviously, I would want to skip Chunk_2.
I've tried a lot of ways to write this in a function. The closest I have gotten is with using the rstudioapi package. Here is what my function looks like:
MyNewFunction <- function(){
rstudioapi::navigateToFile( file = 'Example_Notebook.Rmd' , line = 6 )
Sys.sleep(.2)
rstudioapi::executeCommand(commandId = 'executeCurrentChunk')
Sys.sleep(.2)
print('First Command Complete')
rstudioapi::navigateToFile( file = 'Example_Notebook.Rmd' , line = 15 )
Sys.sleep(.2)
rstudioapi::executeCommand(commandId = 'executeCurrentChunk')
Sys.sleep(.2)
print('Second Command Complete')
}
MyNewFunction()
This runs, but when I look at the Example_Notebook.Rmd file, Chunk_1 displays an output, but Chunk_3 does not.
My cursor ends on line 15, so it seems like it runs through navigateToFile, Sleep commands, and print commands, but it waits for the executeCommand until the entire function has has finished.
I've also tried putting the code in the function in its own file and then using source(), as well as wrapping the code in rstudioapi::sendToConsole() but the same thing occurs.
Its almost like I need to execute 2 separate top-level tasks in a single command, but I'm not sure if that's possible or even techinically makes sense.
Looking at the C++ & java code in Rstudio, it seems like the "Run All Chunks Above" command puts all the chunks in to a scope & uses the function "executeScopedChunks". I unfortunately don't understand C++ or java at all so I don't really understand much more than that. It probably isn't helpful, but just in case, I'm looking at that here:
https://github.com/rstudio/rstudio/blob/master/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/TextEditingTarget.java#L5754
Is there any way to solve this? Any help would be very appreciated!
First, you can try the "visual" version instead of "source" version, it may make life easier:
Then, you can click the "setting" icon to change chunk 2 or whatever chunk that you do not want to run to "Show nothing (don't run the code)":
And if you want to run all the other chunks without knit, you can just click the 'run' button on the top-right of the toolbar. Click "run all" or other commands you like.
I have an R vector of filepaths for pdf figures I would like to put into my knitr document and knit to html. I see that I can get a single pdf to be included with
knitr::include_graphics(filepaths[1])
My filepaths vector is long and changes size between document compilations. Is there a method of including them all in one go. I had imagined this would work.
for(i in filepaths){knitr::include_graphics(i)}
Had also tried:
for(i in filepaths){ print("![](", filepaths[i], ")" ) }
knitr::include_graphics() is vectorized, so the answer is simply:
knitr::include_graphics(filepaths)
Your first solution does not work because knitr::include_graphics() needs to be the top-level expression. Your second solution does not work because you should use cat() instead of print(), and the chunk option results='asis'.
There are several advantages of using include_graphics() over cat() + results='asis'.
Try using cat instead of include_graphics. For example:
for(i in 1:length(filepaths) {
cat("![](", filepaths[i], ")")
}
This is general Markdown syntax: ![NAME](PATH).
With this solution you will need to use results = "asis" in chunk header.
I'm trying to get knitr to create a bibtex file that includes all the packages that I am using as shown (and answered) in this question. That part is working fine but a single R package, foreach, results in non-valid bibtex code.
Here is a minimal .Rnw example that produces the error
\documentclass[11pt]{article}
\usepackage{natbib}
\begin{document}
This is a test
<<>>=
library(foreach)
# Write the bibtex file:
write_bib("foreach", file="test.bib")
#
\nocite{*}
\bibliographystyle{apalike}
\bibliography{test}
\end{document}
kniting this file produces this test.bib file
#Manual{R-foreach,
title = {foreach: Provides Foreach Looping Construct for R},
author = {{Revolution Analytics} and Steve Weston}},
year = {2015},
note = {R package version 1.4.3},
url = {https://CRAN.R-project.org/package=foreach},
}
Note that the author line has two curly braces towards the end of the author line so using this bibtex file without removing the curly brace results in a bunch of problems. I've only encountered this problem with the foreach package.
Can anyone tell me what I can do to prevent the error (currently I have a one-line sed code to remove the extra brace)?
The citation("foreach") output looks fine and dandy, so I'm guessing the error may be deep down in utils:::toBibtex.bibentry but I haven't been able to figure it out.
Is it possible to include R documentation in knitr output? When using stock datasets, it would be nice to just include the builtin documentation without having to copy and paste it in. The problem appears to be that ? works by side effect and so there is no "result" in a meaningful sense. For example,
```{r}
?mtcars
```
has no output that is trapped by knitr.
Using help(...,help_type) instead of ? doesn't help either. I've tried:
```{r, results='markup'}
help(mtcars, help_type="text")
```
and
```{r, results='asis'}
help(mtcars, type="html")
```
with the same result. (In the latter case, knitr did trap the output ## starting httpd help server ... done, which is basically just a message about the side effect.)
In other words, is there a way to extract R help in plain text or HTML?
To answer your specific question, "Is there a way to extract R help in plain text or HTML?", the answer would be to use a combination of Rd2HTML or Rd2txt from the "tools" package, with a little bit of help from .getHelpFile from "utils".
For HTML:
tools:::Rd2HTML(utils:::.getHelpFile(help(mtcars)))
For txt:
tools:::Rd2txt(utils:::.getHelpFile(help(mtcars)))
By the sounds of it, though, you should be able to use the function I've linked to in the comment above. For instance, to include the text from the "Description" section of the "mtcars" help page, you would use something along the lines of:
```{r, echo=FALSE, results='asis'}
cat(helpExtract(mtcars, section = "Desc", type = "m_text"))
```
I think you can get what you want by hacking the pager option as follows:
pfun <- function(files, header, title, delete.file) {
all.str <- do.call("c",lapply(files,readLines))
cat(all.str,sep="\n")
}
orig_pager <- options(pager=pfun)
help("mtcars")
options(orig_pager)
(you can return the character vector from the function instead of cat()ing it if you prefer).
Use printr, e.g.
library(printr)
help(mtcars)
detach('package:printr', unload = TRUE)
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.