R markdown knitting errors with repeated chunks - r

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.

Related

How to run a julia chunk in RMarkdown

I am trying to run a Julia chunk in RMarkdown. I am using the package JuliaCall. Here are the steps I've completed:
Downloaded Julia
Installed JuliaCall
Run the code julia_setup(JULIA_HOME = "C:/Users/James/Documents/Julia 1.5.1/bin")
Run julia <- julia_setup()
Here is a minimal example of my RMarkdown file:
---
title: "julia_eg"
author: "James"
date: "9/23/2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
this is a julia example
```{julia}
a = sqrt(17)
a
```
When I try and knit this, it tells me it cannot find Julia - I get this error:
Error in julia_locate(JULIA_HOME) : Can not find the Julia installation in the default installation path 'C:\Users\James\AppData\Local' Calls: <Anonymous> ... withVisible -> eval -> julia_setup -> julia_locate
So clearly my running of julia_setup in step 3 above didn't have the desired effect - even though it did run this for sometime and told me that it had completed that task.
Is there a more straightforward way of getting it to find Julia?
Rmarkdown is only aware of any code that is run in the immediate session, to avoid creating documents that will be impossible to compile by itself.
As such you'll have to add the code to the initial code chunk
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
Julia_setup(JULIA_HOME = "C:/Users/James/Documents/Julia 1.5.1/bin")
julia <- julia_setup()
```

knitting a figure to word using papaja fails

I am able to knit the following code to PDF. However, it always fails when trying to knit the output to Word (win 10, Rstudio 1.2.5033, R 3.6.2, papaja 0.1.0.9942). I had to delete the papaja header for posting (too much code).
```{r setup, include = FALSE}
library("papaja")
```
# Methods
```{r figure}
plot(cars)
```
The error message reads
Error running filter D:/Boelte/R_library/papaja/rmd/docx_fixes.lua:
[string "--[[..."]:227: Constructor for Emph failed: [string
"--[[..."]:258: attempt to index a nil value (local 'x')
stack traceback: [C]: in function 'error'
..."]:227: in field 'Emph' D:/Boelte/R_library/papaja/rmd/docx_fixes.lua:14: in function 'Image'
Fehler: pandoc document conversion failed with error 83
Is there any way to correct this error? It is a papaja or a pandoc error?
This is a papaja error related to post-processing of the document (in this case styling figure captions) via the docx_fixes.lua-filter. I will try to fix this as soon as possible. For the time being, you should be able to resolve this problem by specifying a figure caption in the chunk options.
```{r setup, include = FALSE}
library("papaja")
```
# Methods
(ref:fig-cap) This is the figure caption.
```{r figure, fig.cap = "(ref:fig-cap)"}
plot(cars)
```

How to solve R Markdown (Knit) "'closure' is not subsettable"?

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)
```

Using knitr to create HTML slides and separate R code file

Following on from this question... I am not sure where to set knitr option if I want to output a separate file of R code. The following does not provide the expected additional .R files in my working directory.
---
output: ioslides_presentation
---
```{r setup, include=FALSE}
library("knitr"); purl("myfile.rmd")
#library("knitr"); knit("test_tangle.Rmd", tangle = TRUE)
#opts_knit$set(tangle=TRUE)
```
## Slide with Plot
```{r, echo=TRUE}
plot(cars)
```
but an error message...
Quitting from lines 6-7 (myfile.rmd)
Error in readLines(if (is.character(input2)) { :
cannot open the connection
Calls: <Anonymous> ... withVisible -> eval -> eval -> purl -> knit -> readLines
Execution halted
I recommend you to use the hook_purl function instead. The function purl() (or equivalently, knit(tangle = TRUE)) may fail to work in certain cases, and the hook function hook_purl() is more reliable. See ?hook_purl for more information.
---
output: ioslides_presentation
---
```{r setup, include=FALSE}
library("knitr")
knit_hooks$set(purl = hook_purl)
```
## Slide with Plot
```{r, echo=TRUE}
plot(cars)
```
Then as you knit the document, the R script will be automatically generated.

How to knit a child document from a URL

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")
```

Resources