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)
```
Related
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.
The issue I'm having is after I knit my R-Markdown file to a pdf (or word) document, I get the following error:
However, I have made sure the I have my library(psych) call in my r in which the code chunks are being called from. The describe() call works just fine when I call it in my .r file in r studio, and when I call it inline in the markdown file, but I still get the error when I knit to pdf.
Knitr code referenced in .r file.
## #knitr code_2.2
library(psych)
describe(women_DF)
code chunk in r markdown:
## 2.2 Summarize using describe()
* The `summary` function in base R does not show the number of observations and standard deviation of each variable
+ A convenient alternative to `summary` that includes these statistics is `describe` in the `psych` package
* If you have not already done so, install the `psych` package
+ Console: install.packages("psych") or from Packages → Install dialog
* Recall that you must also call `library(psych)` to load the package into memory
* Now use `describe()` to summarize `women_DF`:
```{r code_2.2}
Setup of r markdown file:
---
title: "Module 1 Workshop"
author: "MSBX-5310 (Customer Analyitcs)"
date: "1/14/2021"
output:
pdf_document: default
word_document: default
---
```{r, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
fig.height = 3,
fig.width = 4,
message = FALSE,
comment = NA, error = TRUE)
#uncomment the line below if using an external R script for R chunks
knitr::read_chunk("Workshop1.R")
knitr runs code in its own R session when you click the knit button. This means that anything you have in your environment is not available to that separate session building your document.
In particular, although you did not post your entire Rmarkdown file, it seems the problem is that you didn't load the psych package anywhere in your .Rmd file. You shoould load it somewhere in the Rmarkdown file, either in a separate chunk (if you don't want it to show just before your function call) or in the same chunk where you call one of its functions (in this case, describe()).
```{r code_2.2}
library(psych)
describe(women_DF)
There are a few questions about this already, but they are either unclear or provide solutions that don't work, perhaps because they are outdated:
Proper R Markdown Code Organization
How to source R Markdown file like `source('myfile.r')`?
http://yihui.name/knitr/demo/externalization/
Modularized code structure for large projects
R Markdown/Notebook is nice, but the way it's presented, there is typically a single file that has all the text and all the code chunks. I often have projects where such a single file structure is not a good setup. Instead, I use a single .R master file that loads the other .R files in order. I'd like to replicate this structure using R Notebook i.e. such that I have a single .Rmd file that I call the code from multiple .R files from.
The nice thing about working with a project this way is that it allows for the nice normal workflow with RStudio using the .R files but also the neat output from R Notebook/Markdown without duplicating the code.
Minimal example
This is simplified to make the example as small as possible. Two .R files and one master .Rmd file.
start.R
# libs --------------------------------------------------------------------
library(pacman)
p_load(dplyr, ggplot2)
#normally load a lot of packages here
# data --------------------------------------------------------------------
d = iris
#use iris for example, but normally would load data from file
# data manipulation tasks -------------------------------------------------
#some code here to extract useful info from the data
setosa = dplyr::filter(d, Species == "setosa")
plot.R
#setosa only
ggplot(setosa, aes(Sepal.Length)) +
geom_density()
#all together
ggplot(d, aes(Sepal.Length, color = Species)) +
geom_density()
And then the notebook file:
notebook.Rmd:
---
title: "R Notebook"
output:
html_document: default
html_notebook: default
---
First we load some packages and data and do slight transformation:
```{r start}
#a command here to load the code from start.R and display it
```
```{r plot}
#a command here to load the code from plot.R and display it
```
Desired output
The desired output is that which one gets from manually copying over the code from start.R and plot.R into the code chunks in notebook.Rmd. This looks like this (some missing due to lack of screen space):
Things I've tried
source
This loads the code, but does not display it. It just displays the source command:
knitr::read_chunk
This command was mentioned here, but actually it does the same as source as far as I can tell: it loads the code but displays nothing.
How do I get the desired output?
The solution is to use knitr's chunk option code. According to knitr docs:
code: (NULL; character) if provided, it will override the code in the
current chunk; this allows us to programmatically insert code into the
current chunk; e.g. a chunk option code =
capture.output(dump('fivenum', '')) will use the source code of the
function fivenum to replace the current chunk
No example is provided, however. It sounds like one has to feed it a character vector, so let's try readLines:
```{r start, code=readLines("start.R")}
```
```{r plot, code=readLines("start.R")}
```
This produces the desired output and thus allows for a modularized project structure.
Feeding it a file directly does not work (i.e. code="start.R"), but would be a nice enhancement.
For interoperability with R Notebooks, you can use knitr's read_chunk method as described above. In a notebook, you must call read_chunk in the setup chunk; since you can run notebook chunks in any order, this ensures that the external code will always be available.
Here's a minimal example of using read_chunk to bring code from an external R script into a notebook:
example.Rmd
```{r setup}
knitr::read_chunk("example.R")
```
```{r chunk}
```
example.R
## ---- chunk
1 + 1
When you execute the empty chunk in the notebook, code from the external file will be inserted, and the results displayed inline, as though the chunk contained that code.
As per my comment above, I use the here library to work with projects in folders:
```{ r setup, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
library(here)
insert <- function(filename){
readLines(here::here("massive_report_folder", filename))
}
```
and then each chunk looks like
```{ r setup, echo=FALSE, message=FALSE, warning=FALSE,
results='asis', code=insert("extra_file.R")}
```
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'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")
```