rr-markdown

Remove all objects from a chunk


Sometimes, I only need some objects for a single chunk, but they are sometimes also heavy for the environment (e.g. list of dataframes).

I was wondering if there was a solution for removing all objects created from a chunk after it has been launched (either using "Run current chunk" or "knit")?

For example the following chunk would create the object listDfForML, this list is used to analyse stuff, but at the end I would like to remove this list without having to call for rm(listDfForML).

```{r myChunk}
##### Initiating object
listDfForML <- 
  list(
    data.frame(value=rnorm(100),
               group=rep(c("A", "B"), each=50)),
    data.frame(value=rnorm(100),
               group=rep(c("C", "D"), each=50))
    )


##### Perform analyses
lapply(listDfForML, function(x) mean(x$value))
```

Solution

  • We can use chunk hooks. Assume that our test-clean.Rmd file looks like this which is the same as in the question except for the first line.

    ```{r myChunk, clean=TRUE}
    ##### Initiating object
    listDfForML <- 
      list(
        data.frame(value=rnorm(100),
                   group=rep(c("A", "B"), each=50)),
        data.frame(value=rnorm(100),
                   group=rep(c("C", "D"), each=50))
        )
    
    
    ##### Perform analyses
    lapply(listDfForML, function(x) mean(x$value))
    ```
    

    Then create a clean hook and knit the file like this:

    library(knitr)
    knit_hooks$set(clean = local({
      .ls <- NULL
      function(before, options, envir, name) {
        if (before) .ls <<- ls(envir = envir)
        else rm(list = setdiff(ls(envir = envir), .ls), envir = envir)
      } 
    }))
    knit("test-clean.Rmd")
    

    It is also possible to globally apply the hook. See the link above.