Menu Home

Using unpack to Manage Your R Environment

In our last note we stated that unpack is a good tool for load R RDS files into your working environment. Here is the idea expanded into a worked example.

# remotes::install_github("WinVector/wrapr")
library(wrapr)

a <- 5
b <- 7
do_not_want_1 <- 13
do_not_want_2 <- 15

# save the elements of our workspace we want
saveRDS(as_named_list(a, b, do_not_want_1), 'example_data.RDS')

# clear values out of our workspace for the example
rm(list = ls())
ls()
#> character(0)
# notice workspace environemnt now empty

# read back while documenting what we expect to
# read in
unpack[a, b] <- readRDS('example_data.RDS')

# confirm what we have, the extra unpack is a side
# effect of the []<- notation. To avoid this instead
# use one of:
#   unpack(readRDS('example_data.RDS'), a, b)
#   readRDS('example_data.RDS') %.>% unpack(., a, b)  # notice dot
#   readRDS('example_data.RDS') %.>% unpack[a, b]
#   readRDS('example_data.RDS') %.>% to(a, b)         # no dot
#   readRDS('example_data.RDS') %.>% to[a, b]
ls()
#> [1] "a"      "b"      "unpack"
# notice do_not_want_* are not present
# do_not_want_2 was dropped when we wrote the RDS
# do_not_want_1 was not specified during the unpack, so dropped

print(a)
#> [1] 5

print(b)
#> [1] 7

We have new documentation on the new as_named_list helper function here.

The idea is: this is a case where non-standard evaluation is working for us (and clarity/safety) as it forces the user to document each object they want written out (by explicitly naming them), and exactly what objects they expect to come back (again by explicitly naming them right at the assignment location).

Categories: Tutorials

Tagged as:

jmount

Data Scientist and trainer at Win Vector LLC. One of the authors of Practical Data Science with R.

2 replies

  1. Very interesting post and useful package – thanks for making it freely available.
    I think the code example above has a small bug which might mislead some readers. The object ‘do_not_want’ is not saved in the RDS file, so its not surprising that its not loaded by unpack().
    Change
    saveRDS(as_named_list(a, b), ‘example_data.RDS’)
    to
    saveRDS(as_named_list(a, b, do_not_want), ‘example_data.RDS’)

    1. Thanks for your comment. I see your point.

      My intent of the example was to show one could drop items on save or on load (and an error is thrown if you ask for an item that is not there). In both the save case and load case we can cut down on what is used.

      I have updated the example to work with your critique. Thanks again.

      So your variation is also interesting. I now have more and better examples in the new vignette here.

%d bloggers like this: