1

I started using the below code in my scripts to clear the environment before every run.

# Clear environment
rm(list = ls())

This works great in R scripts. However, when I Knit the below RMarkdown document in RStudio, my environment variables are not clearing.

To test, run myNewVariable <- 2 in the console, then Knit the below RMarkdown document. When I do this, myNewVariable still exists. Is this normal?

---
title: "Clear Environment"
author: "John"
date: "August 17, 2015"
output: html_document
---

```{r}  
# Clear environment
rm(list = ls())
```
John Tarr
  • 717
  • 1
  • 9
  • 21
  • 1
    `knitr` creates a completely separate environment for the code to run in. it has nothing to do with the environment you have open in RStudio. – hrbrmstr Aug 20 '15 at 12:17
  • Thank you. If you want to post that as the answer, I'll accept it. Based on how quickly you answered, I'm sure I missed the answer in search, but I didn't find it. Might help someone else to have the answer. – John Tarr Aug 20 '15 at 12:19
  • 1
    @hrbrmstr, I had posted a similar comment, but then I saw [this](http://stackoverflow.com/a/8437393/1270695) so I thought I would dig some more.... – A5C1D2H2I1M1N2O1R2T1 Aug 20 '15 at 12:24
  • @AnandaMahto that's super-interesting, esp since I get bit by forgetting to put a data frame or two into an Rmd almost weekly :-) I'll poke at it a bit more as well. – hrbrmstr Aug 20 '15 at 12:25
  • I think @Yihui is referring to the `knitr` global environment that gets setup at the start of a knit session. See: http://rud.is/dl/env.gif (gif'd screen recording) for example showing `knitr` doesn't see the RStudio/R main global environment. – hrbrmstr Aug 20 '15 at 12:37
  • 1
    When you hit the [knit] button RStudio spans a new process with fresh R session. If you do it with `rmarkdown::render` then `knitr` will see your environment. – bergant Aug 20 '15 at 15:26

0 Answers0