This tutorial shows you various methods to save and load objects efficiently within the R environment. Whether you are working on statistical analyses or large dataset, it is important to store data and retrieve it later so that you don't need to run the lengthy code again.
Saving Data Files in Your R Session
In R, the saveRDS function is used to save a single object for later use. In the code below, we are saving the 'mydata' dataframe as 'logistic.rds'. You can save any object of your choice, not just dataframes.
saveRDS(mydata, "logistic.rds")
Loading Stored Data from Your R Session
To bring back what you saved, you use readRDS. This is the opposite of saveRDS.
mydata = readRDS("logistic.rds")
Note : You can define any name other than mydata.
Method 2 : Saving Data in R session
Another approach to saving data within an R session is using the save function
save(mydata,file="E:\\logistic.rdata")
This method stores the 'mydata' object in a file named 'logistic.rdata'. The subsequent loading process involves using the load function.
load("E:\\logistic.rdata")
The following code loads the "logistic.rdata" file into the new environment named "ex" and then list the objects within that environment using the ls() function. Loading data into a new environment helps prevent naming conflicts. If the loaded data contains objects with names that already exist in your current R environment, using a new environment ensures that these objects won't overwrite or interfere with your existing objects.
load("E:\\logistic.rdata", ex <- new.env())
ls(ex)
Saving multiple objects in R session
The save function is also useful for scenarios involving multiple objects. The following code saves both the 'mydata' and 'data2' objects within the '1.RData' file.
save(mydata, data2, file="1.RData")
Saving everything in R session
In R, the save.image function is used to save whole R session.
save.image(file="1.RData")
How does Is(ex) work? And how are you ensuring that the dataset us being loaded in new environment?
ReplyDeleteok
ReplyDelete