issues knitting R markdown to pdf with psych package - r

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)

Related

R Studio: How to load a variable into the Global Environment by running a Knitr document

When I run a knitr document in R Studio, a variable is assigned. I can see this from the generated PDF-file.
Although this variable is not loading into my Global Environment.
My working directory is set in the knitr document. In R studio I use the same working directory.
Is there a method to load the variables into my Global Environment by using knitr?
Thank you.
This is the code:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document.
```{r section1, echo=TRUE}
getwd()
# set the URL for the download
wwwTrain <- "http://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv"
training <- read.csv(url(wwwTrain))
```
You can manually render your document within the global environment by executing this in the RStudio console:
rmarkdown::render("my_document.Rmd", envir=.GlobalEnv)
I do this frequently and wrote an RStudio Addin for this purpose.

How can I print the function description of an R package to Rmarkdown instead of terminal?

Using R markdown and trying to write a small document for the group I'm working in. I wanted to be able to print a functions description directly into the Rmarkdown document I'm writing. For example if I wanted the description for the function "cor" I would use
?cor
And this prints the description in the terminal I'm working on. Now using
print(?cor)
Or
dummy <- ?cor
print(dummy)
doesn't print the description to the Rmarkdown file, but instead again prints in inside the terminal and hangs, until the user exits at which point the RMarkdown pdf is generated. Unfortunately there is no sign of it within the pdf.
How can I make R print this to Rmardkdown and not the terminal?
What you need is the printr package. Make sure you install it before using the example Rmarkdown code below (i.e. run install.packages('printr') first), but here's an example of how to include a help file in an Rmarkdown created PDF:
---
title: "SO"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Printing Help
```{r}
library(printr)
help(sum)
```

Modularized R markdown structure

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

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

GitHub displays all code chunks from README.rmd (despite include=FALSE)

I am currently writing a documentation for an R package hosted on GitHub. I use knitr along with R Markdown to write the README file. Hitting the 'Knit HTML' button in RStudio produces an HTML like I would expect it.
However, pushing README.rmd to GitHub results in what you see in the lower page section when following the above link. For example, the topmost code chunk is declared as follows in the README.rmd file:
```{r global_options, include = FALSE}
library(knitr)
options(width = 120)
opts_chunk$set(fig.width = 12, fig.height = 8, fig.path = 'Figs/',
include = TRUE, warning = FALSE, message = FALSE)
```
However, the include = FALSE statement in the first line of code is simply ignored in this case, and the piece of code that was supposed to be hidden is displayed on the referring GitHub page. In addition, results (e.g. from plot(), head()) are not visualized although opts_chunk$set(..., include = TRUE).
Did anyone encounter a similar problem and can me help me get my README document displayed correct, i.e. in the way RStudio would handle it, on GitHub?
The readme file you are trying to publish on github should be a plain markdown document i.e., a .md file and not the raw .rmd. So first you knit the .rmd with knitr (within R) as follows:
knit(input="readme.rmd", output = "readme.md") #see ?knit for more options
That will evaluate the global and chunk options specified in the source .rmd and produce a .md that's formatted accordingly and which github can render readily.
For more information on using an .Rmd to generate the .md see the Readme.Rmd section of http://r-pkgs.had.co.nz/release.html
You can also have devtools set up this automatically for your package using devtools::use_readme_rmd().

Resources