Search code examples
rr-markdownknitrpsych

issues knitting R markdown to pdf with psych package


The issue I'm having is after I knit my R-Markdown file to a pdf (or word) document, I get the following error:enter image description here

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.

enter image description here

enter image description here

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

Solution

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