I am attempting to pull R code chunks over HTTPS from an R script into a LaTeX document.
The .R file is in rstudio server and shared via webdav.
The LaTeX document resides on a server that cannot store files locally (ShareLaTeX).
Therefore, to get around the problem, I thought I'd use URL calls,
the following works for pulling in data:
<<load_data, echo=FALSE, cache=FALSE>>=
library(RCurl)
x <- getURL("https://user:pass#my.webdav.server.net/webdav/data/data.csv")
y <- read.csv(text = x,stringsAsFactors=FALSE,na.strings = "NA")
y
#
However, I would also like to pull in code chunks.
I have tried the following:
<<external-code, cache=FALSE>>=
z<-getURL("https://user:pass#my.webdav.server.net/webdav/model.R")
read_chunk(z, lines = code, labels = "foo")
#
However, this returns the error:
error in read_chunk(z, lines = code, labels = "foo"): object `code` not found
Is there some way to make knitr parse this variable as a file, or read the external URL?
Related
I use Windows and try to read .Rdata file to RMarkdown using rio's import function. It keeps giving me errors. This works just fine when I'm using R code in the same folder.
So here is the code in the first RMarkdown code chunk
{r setup, include = FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(tidyverse)
library(rio)
df_clean <- import("data/df_clean.rdata")
Error in import("data/df_clean.rdata") : No such file
Is there a different between using R Code or RMarkdown? This also works fine when I type it in the R console, but doesn't work in the R Code chunk in the RMarkdown.
When I check in the working directory, the file is there
> getwd()
[1] "C:/Users/Project/Project A"
> list.files()
[1] "code" "data"
[3] "documentation" "output"
> list.files("data")
[1] "archive" "df_clean.rdata" "df_unique.rdata"
I'm new to R and just start coding this year. I hope I can do my EDA in RMarkdown to become more organized. Kindly help me with the question format if I did not posted it correctly.
if you unsure of the file path of the RData to import, use this to make Selection manually first..
df_clean <- import(file.choose())
or you can also get the full path of your RData stored in variable by doing:
RData_path <- file.choose()
df_clean <- import(RData_path)
I'm writing a personal use package which trains/tests models, and finally runs a myriad of LIME and DALEX explanations on them. I save these as their own ggplot2 objects (say lime_plot_1), and at the end of the function these are all returned to the global environment.
However, what I would like to have happen is that, at the end of the function, not only would I have these graphs in the environment but a small html report would also be rendered - containing all the graphs that were made.
I would like to point out that while I do know I could do this by simply using the function within an Rmarkdown or Rnotebook, I would like to avoid that as I plan on using it as an .R script to streamline the whole process (since I'll be running this with a certain frequency), and from my experience running big chunks in .Rmd tends to crash R.
Ideally, I'd have something like this:
s_plot <- function(...){
1. constructs LIME explanations
2. constructs DALEX explanations
3. saves explanations as ggplot2 objects, and list them under graphs_list
4. render graphs_list as an html file
}
1, 2, and 3 all work but I haven't found a way to tackle 4. that doesn't include doing the whole process in a .Rmd file.
EDIT: Thanks to #Richard Telford's and #Axeman's comments, I figured it out. Below is the function:
s_render <- function(graphs_list = graphs_list, meta = NULL, cacheable = NA){
currentDate <- Sys.Date()
rmd_file <- paste("/path/to/folder",currentDate,"/report.Rmd", sep="")
file.create(rmd_file)
graphs_list <- c(roc_plot, prc_plot, mp_boxplot, vi_plot, corr_plot)
c(Yaml file headers here, just like in a regular .Rmd) %>% write_lines(rmd_file)
rmarkdown::render(rmd_file,
params = list(
output_file = html_document(),
output_dir = rmd_file))}
First, create a simple Rmarkdown file, that takes a parameter. The only objective of this file is to create the report. You can for instance pass a file name:
---
title: "test"
author: "Axeman"
date: "24/06/2019"
output: html_document
params:
file: 'test.RDS'
---
```{r}
plot_list <- readRDS(params$file)
lapply(plot_list, print)
```
I saved this as test.Rmd.
Then in your main script, write the plot list to a temporary file on disk, and pass the file name to your markdown report:
library(ggplot2)
plot_list <- list(
qplot(1:10, 1:10),
qplot(1:10)
)
file <- tempfile()
saveRDS(plot_list, file)
rmarkdown::render('test.Rmd', params = list(file = file))
An .html file with the plots is now on your disk:
I'm attempting to make my code more modular: data loading and cleaning in one script, analysis in another, etc. If I were using R scripts, this would be a simple matter of calling source on data_setup.R inside analysis.R, but I'd like to document the decisions I'm making in an Rmarkdown document for both data setup and analysis. So I'm trying to write some sort of source_rmd function that will allow me to source the code from data_setup.Rmd into analysis.Rmd.
What I've tried so far:
The answer to How to source R Markdown file like `source('myfile.r')`? doesn't work if there are any repeated chunk names (a problem since the chunk named setup has special behavior in Rstudio's notebook handling). How to combine two RMarkdown (.Rmd) files into a single output? wants to combine entire documents, not just the code from one, and also requires unique chunk names. I've tried using knit_expand as recommended in Generate Dynamic R Markdown Blocks, but I have to name chunks with variables in double curly-braces, and I'd really like a way to make this easy for my colaborators to use as well. And using knit_child as recommended in How to nest knit calls to fix duplicate chunk label errors? still gives me duplicate label errors.
After some further searching, I've found a solution. There is a package option in knitr that can be set to change the behavior for handling duplicate chunks, appending a number after their label rather than failing with an error. See https://github.com/yihui/knitr/issues/957.
To set this option, use options(knitr.duplicate.label = 'allow').
For the sake of completeness, the full code for the function I've written is
source_rmd <- function(file, local = FALSE, ...){
options(knitr.duplicate.label = 'allow')
tempR <- tempfile(tmpdir = ".", fileext = ".R")
on.exit(unlink(tempR))
knitr::purl(file, output=tempR, quiet = TRUE)
envir <- globalenv()
source(tempR, local = envir, ...)
}
I have a shiny app that allows the user to download an HTML file (knitted from a .Rmd file) that includes the code used to run the analysis based on all the user inputs. I am trying to write the base .Rmd file that gets altered when user inputs vary. I am having trouble including user input variables (e.g. input$button1) into R code chunks. Say the user input for input$button1 = "text1".
```{r}
results <- someFun(input$button1)
```
And I'd like to have it knitted like this:
```{r}
results <- someFun('text1')
```
Every time I download the knitted HTML though, I get input$button1 getting written to file. I would also like to be able to produce an .Rmd file that is formatted with this substitution. It seems like knit_expand() might be the key, but I can't seem to relate available examples to my specific problem. Is the proper way to knit_expand() the whole .Rmd file and specify explicitly all the parameters you want subbed in, or is there a more elegant way within the .Rmd file itself? I would prefer a method similar to this, except that instead of using the asis engine, I could use the r one. Any help would be greatly appreciated. Thanks!
Got it. Solution below. Thanks to Yihui for the guidance. The trick was to knit_expand() the whole .Rmd file, then writeLines() to a new one, then render. With hindsight, the whole process makes sense. With hindsight.
For the example, p1 is a character param 'ice cream' and p2 is an integer param 10. There is a user-defined param in ui.R called input$mdType that is used to decide on the format provided for download.
Rmd file:
Some other text.
```{r}
results <- someFun("{{p1}}", {{p2}})
```
in the downloadHandler() within server.R:
content = function(file) {
src <- normalizePath('userReport.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'userReport.Rmd')
exp <- knit_expand('userReport.Rmd', p1=input$p1, p2=input$p2)
writeLines(exp, 'userReport2.Rmd')
out <- rmarkdown::render('userReport2.Rmd', switch(input$mdType,
PDF = pdf_document(), HTML = html_document(), Word = word_document()))
}
file.rename(out, file)
}
Resulting userReport2.Rmd before rendering:
```{r}
results <- someFun("ice cream", 10)
```
I am using the LaTeX package problems to create solution sets from a database of problems. The database is structured like a bibliography database, in a .bib file. The whole system works beautifully for regular LaTeX, but now some of my solutions have R code (in knitr chunks) in them.
The default sequence of knitting/TeXing/BibTeXing in RStudio is not working-- the code ends up in the document verbatim, along with mangled versions of the chunk delimiters. So, I need to find the right workflow of steps to ensure that the code makes it through.
This package seems to be very set on having two files, one for the database and one for the .tex/.rnw, so I can't make a working example, but something like this:
\documentclass{article}
\usepackage[solution]{problems}
\Database{
#QUESTION{1.1,
problem = {1.1},
solution = {This solution only uses TeX, like $\bar{x}$. It works fine.}}
#QUESTION{1.2,
problem = {1.2},
solution = {This solution includes code
<<>>=
head(iris)
#
It does not work.
}}}
\begin{document}
Problems for this week were 1.1 and 1.2
\problems{1.1}
\problem{1.2}
\end{document}
You will have to knit the .bib file first and then run LaTeX and BibTeX.
While you usually have a .Rnw file that is knitted to .tex and then let LaTeX tools process the .tex and the .bib file you will have to start with a (let's call it) .Rbib file that is knitted to .bib and then processed by LaTeX.
For simplicity, I give the file I called .Rbib above the name bibliography.Rnw but you can choose any extension you like. I chose .Rnw because the syntax used inside is the same as in .Rnw files.
As dummy entries for the bib-file I use data from verbosus.com and added some knitr code.
The first chunk sets global chunk options to prevent knitr from adding the code of the chunks or any markup to the output file. The next chunk shows how for example the title field could be filled with generated content and the \Sexpr{} part is an example how this could be used to add some dynamic text.
<<setup>>=
library(knitr)
opts_knit$set(
echo = FALSE,
results = "asis"
)
#
article{article,
author = {Peter Adams},
title = {
<<echo=FALSE, results = "asis">>=
cat("The title of the work")
#
},
journal = {"The title of the journal"},
year = 1993,
number = 2,
pages = {201-213},
month = 7,
note = {An optional note},
volume = 4
}
#book{book,
author = {Peter Babington},
title = {\Sexpr{"The title of the work"},
publisher = {The name of the publisher},
year = 1993,
volume = 4,
series = 10,
address = {The address},
edition = 3,
month = 7,
note = {An optional note},
isbn = {3257227892}
}
It is important to have the chunk option results = "asis" and to use cat() instead of print(). Otherwise, there would be unwanted characters in the output.
If this is saved as bibliography.Rnw the following is enough to get a .bib file with the chunks evaluated:
knit(input = "bibliography.Rnw", output = "bibliography.bib")
After that only standard LaTeX compilation remains.