This page might be helpful to you: http://stat545.com/block002_hello-r-workspace-wd-project.html
(For maximum benefit, I recommend not only reading through it, but also following along trying things in your console as you go)
Something to keep in mind is that you are working towards writing R script files that will recreate all your important objects (data frames, variables, etc) whenever you run them, rather than relying on saving objects to disk. This is different from working, say, with a spreadsheet where the instructions (the formulas) and the results are all mixed up together in a single file.
For your typical experienced R user, saving R objects to disk individually is actually a fairly rare activity. When it is necessary to do so, I think it's a bit safer to use saveRDS()
and readRDS()
instead of save()
and load()
.
The reason is that when you load()
an object that you saved with save()
, it appears in your environment with the same name it had when you originally saved it. If you have some other object in your environment with that name, then it will be replaced with the one you just loaded, with no warning or opportunity to stop the process. By comparison, readRDS()
requires you to explicitly assign a name to the result of reading the object back in, so it can't accidentally overwrite something else in your environment.
Here's a very silly example:
save()
and load()
my_pet <- "Rover the dog"
# This command shows all the objects in my environment
ls.str()
#> my_pet : chr "Rover the dog"
save(my_pet, file = "my_dog.Rdata")
# Much later...
my_pet <- "Whiskers the cat"
ls.str()
#> my_pet : chr "Whiskers the cat"
# Oh wait, I have another pet, too
load("my_dog.Rdata")
# No more Whiskers :-(
ls.str()
#> my_pet : chr "Rover the dog"
Created on 2018-10-30 by the reprex package (v0.2.1)
saveRDS()
and readRDS()
my_pet <- "Rover the dog"
ls.str()
#> my_pet : chr "Rover the dog"
saveRDS(object = my_pet, file = "my_dog.RDS")
# Much later...
my_pet <- "Whiskers the cat"
ls.str()
#> my_pet : chr "Whiskers the cat"
# Oh wait, I have another pet, too
my_other_pet <- readRDS("my_dog.RDS")
# Dogs and cats living peacefully together
ls.str()
#> my_other_pet : chr "Rover the dog"
#> my_pet : chr "Whiskers the cat"
Created on 2018-10-30 by the reprex package (v0.2.1)