I'd like to pull child documents from github to knit as child items inside an rmarkdown document.
Using yihui's example from allowing child markdown files we can have a main doc (modified) that refers to the child doc on github instead of downloading it first.
I've resolved a Windows compatibility issue, and am now getting a setwd() fail.
How do you correctly setup a knitr document to knit child items from a URL? (if possible)
Initial (on windows)
You can also use the `child` option to include child documents in markdown.
```{r test-main, child='https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd'}
```
You can continue your main document below, of course.
```{r test-another}
pmax(1:10, 5)
```
Error output
## Quitting from lines 4-4 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd)
## Error in readLines(if (is.character(input2)) { :
## cannot open the connection
## Calls: <Anonymous> ... process_group.block -> call_block -> lapply -> FUN -> knit -> readLines
## In addition: Warning message:
## In readLines(if (is.character(input2)) { : unsupported URL scheme
## Execution halted
This was erroring because the readLines command was unable to access HTTPS by default when working on Windows.
v2 (on windows)
To correct for the readLines issue I added a chunk that adds the ability to access HTTPS
You can also use the `child` option to include child documents in markdown.
```{r setup, results='hide'}
setInternet2(use = TRUE)
```
```{r test-main, child='https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd'}
```
You can continue your main document below, of course.
```{r test-another}
pmax(1:10, 5)
```
Error output
## processing file: https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd
## Quitting from lines 2-2 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd)
## Quitting from lines NA-7 (https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd)
## Error in setwd(dir) : cannot change working directory
## Calls: <Anonymous> ... process_group.inline -> call_inline -> in_dir -> setwd
## Execution halted
Trying to add in a setwd("~") into chunk setup has no impact on the error message
I don't think you can do this because as I understand it, there is a directory change (to the child document's directory) during knitting. Because your child document is not a local file, the implicit setwd will fail.
A solution would be to add a hidden chunk that downloads the github file to a temporary directory and then deletes the downloaded file. Something like:
```{r setup, echo=FALSE, results='hide'}
setInternet2(use = TRUE)
x <- tempfile(fileext = "Rmd")
on.exit(unlink(x))
download.file("https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd", x)
```
```{r test-main, child=x}
```
You can continue your main document below, of course.
```{r test-another}
pmax(1:10, 5)
```
If the child is only markdown (no R code to process), then this may work for you.
```{r footer, echo=FALSE, results='asis'}
url <- "https://raw.githubusercontent.com/yihui/knitr/master/inst/examples/child/knitr-child.Rmd"
childtext <- readLines(url)
cat(childtext, sep="\n")
```
Related
I am new to Stackoverflow - so please excuse any possible strangeness in my post.
I have a simmilar question as Tom, posted here.
I want to save a pdf created by markdown in a specific directory. After several unsuccessful attempts (including a frustrating chat with GPT), I followed starjas instructions in the post mentioned, yet unsuccessfully.
Here's my YAML header:
---
title: 'MyTitle'
subtitle: 'Analysis XYZ'
author: "Boris et al."
date: "2023-01-22"
knit: (function(input, encoding) {
rmarkdown::render(input,
encoding = "UTF-8",
output_dir = "05-Reports")})
output: pdf_document
---
… and here some code snippets from the scripts main body:
knitr::opts_chunk$set(echo = FALSE, message = TRUE)
source("02-Scripts/03-LogMod-6-plot.R", local = knitr::knit_global())
{r model results} model6.res.table <- simple_kable <- knitr::kable(model6.res, format = "pipe") model6.res.table
Here's the error message I get:
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
Calls: <Anonymous> ... eval_with_user_handlers -> eval -> eval -> source -> file
Execution halted
I believe that the problem has to do something with R not being able to find the output-directory specified (05-Reports). But I have no clue why, as this output-directory is within the working directory:
getwd()
[1] "/Users/my-User/Documents/studyXYZ/1-XYZdata/6-R/studyXYZ-R-Project"
list.files()
[1] "01-Data" "02-Scripts" "03-Outputs"
[4] "04-Plots" "05-Reports" "studyXYZ-R-Project.Rproj"
Maybe important to know: I am working with a R-project. Furthermore, in the Global Options under R Markdown, I set "Evaluate chunks in directory:" "Project", as Julius Diel mentioned in a thread regarding a similar topic:
"Error "cannot open the connection" in executing "knit HTML" in RStudio"
Before setting R's Global Options like this, I had other issues regarding the scource()-command from my markdown-script adressing the R-scripts containing the analysis-commands. Now the scourcing works fine and I get the results as expected when conducting the markdown script without specifying the output directory (in html and pdf). It's just that the pdf won't be saved where I want it.
Does anyone have a clue what causes this problem?
I didn't know about the option Evaluate chunks in directory: "Project". Previously, I used the following in the setup chunk:
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
However, this option is ignored (as well as the option set in RStudio) when using rmarkdown::render in the header of the document. You need to set knit_root_dir to define the root directory from which you the can specify relative paths in source used in your rmarkdown document:
knit: (function(input, encoding) {
rmarkdown::render(input,
output_dir = "05-Reports",
knit_root_dir = rprojroot::find_rstudio_root_file())})
I included a check to install an R package if it's not already installed by the following syntax:
```{r setup-packages, results=FALSE, message=FALSE, warning=FALSE}
if(! require("readxl")) install.packages("readxl")
```
which returns this error:
processing file: Testing.Rmd
Error in parse_block(g[-1], g[1], params.src, markdown_mode) :
Duplicate chunk label 'setup-packages', which has been used for the chunk:
if(! require("readxl")) install.packages("readxl")
Calls: <Anonymous> ... process_file -> split_file -> lapply -> FUN -> parse_block
Execution halted
The knitting works if I change {r setup-packages, results=FALSE, message=FALSE, warning=FALSE} to {r}.
I want to reuse this chunk {r setup-packages, results=FALSE, message=FALSE, warning=FALSE} for each package but it only works once. Can someone explain or provide a solution to make it work with other packages?
knitr is erroring due to the reuse of a chunk name. Each chunk must be unnamed, as you found works with just {r}, or uniquely named.
You can fix it in any of these ways:
Put the lines for each of your package checks in a single chunk.
Rename each chunk to have a unique name, like setup-packages-readxl.
Set the option options(knitr.duplicate.label = "allow") in your Rprofile, though this is not a recommended use of this power according to the knitr documentation.
I have created a word file from an rmarkdown file using redoc output directly in RStudio and clicking "knit". This works fine.
---
title: "Untitled"
output:
redoc::redoc
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## GitHub Documents
This is an R Markdown format used for publishing markdown documents to GitHub. When you click the **Knit** button all R code chunks are run and a markdown file (.md) suitable for publishing to GitHub is generated.
## Including Code
You can include R code in the document as follows:
```{r cars}
summary(cars)
```
but trying to convert it back to Rmd it throws an error. Has anyone else had that?
redoc::dedoc(docx = "test.docx",overwrite = TRUE)
Error in convert_docx_to_md(docx, track_changes, wrap, verbose, md_only) :
lazy-load database '/Library/Frameworks/R.framework/Versions/3.6/Resources/library/rmarkdown/R/rmarkdown.rdb' is corrupt
In addition: Warning messages:
1: In convert_docx_to_md(docx, track_changes, wrap, verbose, md_only) :
restarting interrupted promise evaluation
2: In convert_docx_to_md(docx, track_changes, wrap, verbose, md_only) :
internal error -3 in R_decompress1
I cannot show object in markdown document that are objects generated in different R script(within the same session). I would like to point out that I am newbie to markdown. So the code is as follows(''' are added before and after):
{r eval=TRUE, echo=FALSE}
head(output_by_size,10) # 1st line
summary(cars) # 2nd line
dim(iris) # 3rd line
when I comment line 2nd and 3rd the following error is generated:
Error in head(output_by_size, 10) : object 'output_by_size' not found
Calls: ... withCallingHandlers -> withVisible -> eval -> eval -> head
When 1st line is commented, lines 2nd and 3rd work as expected. Output_by_size is just simple data frame object. Could you please help me out?
There are 2 ways to load the data "output_by_size" to your .RMD file:
Don't knit your file with the Rstudio "knit" button, save your RMD file and then use the console:
library(knitr)
knit('your_file.Rmd')
This will take your recent environment into account and the error should be gone.
Store your "output_by_size" as "output_by_size.RData" and load it manually in your RMD file
```{r load myData, include=FALSE}
load("output_by_size.RData")
```
If you do it this way you can use the "knit" button from RStudio.
I hope one of this ways is a good solution for you.
I am trying to use RMarkdown (Knit) for the first time to produce pdf. The default file (File > New File > R Markdown) works well, it shows the generated pdf when compiled. For example, the following code runs,
```{r cars}
summary(cars)
```
However, if I just change cars with "myData," it does not compile and shows,
Error in object[[i]] : object of type 'closure' is not subsettable
Calls: <Anonymous> ... withVisible -> eval -> eval -> summary -> summary.default
Execution halted
I have "myData" loaded in the global-environment and can do other operations in original R script. Can someone please provide some guideline. Thank you very much for your time.
Running an Rmarkdown file starts a new R session.
Within the new session, you can load the data.frames that are stored in the data package, but other datasets must be loaded from within the Rmarkdown document.
To get myData to show up in your Rmarkdown document,
save the file somewhere with save in your current R session
then in your Rmarkdown document, use load to open up the data set
So, in your current R session:
save(myData, file="<path>/myData.Rdata")
and in your Rmarkdown file:
```{r myDataSummary}
load("<path>/myData.Rdata")
summary(myData)
```
If your data is stored as a text file, and you don't wish to store a separate .R file, use read.csv or friend directly within your Rmarkdown file.
```{r myDataSummary}
myData <- read.csv("<path>/myCSV.csv")
summary(myData)
```
This is the error you get when you try to subset (= via x[i]) a function. Since this error is caused by summary(cars) in your code, we may surmise that the cars object refers to a function in the scope in which the document is knit.
You probably forgot to load your data, or you have a function with the same name defined in the current scope.
As #Imo explained, the basic problem is the new session. So, the answer would be adding the script in the rMarkdown. However, it will create few more hiccups. Here is how I handled few of them,
```{r global_options, include=FALSE}
source(file = "C:\\Path\\to\\my\\file.R")
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE)
```