save
saves the name of the dataset as well as the data. Thus, you should not not assign a name to load("data")
and you should be fine. In other words, simply use:
load("data")
and it will load an object named df
(or whatever is contained in the file "data") into your current workspace.
I would suggest a more original name for your file though, and consider adding an extension to help you remember what your script files are, your data files are, and so on.
Work your way through this simple example:
rm(list = ls()) # Remove everything from your current workspace
ls() # Anything there? Nope.
# character(0)
a <- 1:10 # Create an object "a"
save(a, file="myData.Rdata") # Save object "a"
ls() # Anything there? Yep.
# [1] "a"
rm(a) # Remove "a" from your workspace
ls() # Anything there? Nope.
# character(0)
load("myData.Rdata") # Load your "myData.Rdata" file
ls() # Anything there? Yep. Object "a".
# [1] "a"
str(a) # Is "a" what we expect it to be? Yep.
# int [1:10] 1 2 3 4 5 6 7 8 9 10
a2 <- load("myData.Rdata") # What about your approach?
ls() # Now we have 2 objects
# [1] "a" "a2"
str(a2) # "a2" stores the object names from your data file.
# chr "a"
As you can see, save
allows you to save and load multiple objects at once, which can be convenient when working on projects with multiple sets of data that you want to keep together.
On the other hand, saveRDS
(from the accepted answer) only lets you save single objects. In some ways, this is more "transparent" since load() doesn't let you preview the contents of the file without first loading it.