Search code examples
rr-markdownlocal-variableschunks

Remove variable after chunk is executed


In Rmarkdown, when I execute some code, all variables I created end up in the common namespace of the whole notebook where other chunks can access them. However I often make temporary variables that don't really need to persist after the chunk is over. They clutter up my variable list, my autocomplete dropdown, and generally cause confusion and subtle bugs (eg. if I forget to initialize a variable that was used by a previous chunk).

For example:

Calculate the area of a circle:
```{r}
r = 1.23

pi = 3.14  
temp = 1.23^2

area = pi * temp
```

If I only want r and area to persist after running this, how can I "mark" pi and temp to be cleared after the chunk is done?


Solution

  • Note pi is a built-in constant in R, you do not need to declare your own approximation.

    A good solution is to wrap the content of each chunk in a function. In this case, your chunk would look like this:

    r <- 1.23
    circle_area <- function(x) {
    pi*(r^2)
    }
    area <- circle_area()
    

    If having the function circle_area persist is also a problem, the advice to use rm() is correct. In that case, I'd say if your chunks are sufficiently complex it means you only have to worry about removing one name per chunk.