File operations‎ > ‎

Save & load

Save and load R data

Save and load data in .RData or .rds file format
( see → read & write for saving data as text files )

save()   
- to save one or several variables (including their variable names)
- useful to save all variables of a data analysis project

- to save the pure data content of a single variable (without keeping the variable name)
- useful to save different results, one by one, and later combine the results by importing the individual data in a controlled way

Save multiple variables

# save multiple variables (objects)
x = 23
y = 14
save(x, y, file="data_xy.RData")


# load data into new R environment "ev" to avoid overwriting variables having the same name
x = 44
load("data_xy.RData", envir = (ev = new.env()) )

ev$x
 [1] 23
ev$y
 [1] 14
x
 [1] 44


# load data (without new environment): overwrites all variables in R that have the same name
x = 44 # will be overwritten by identical variable "x" in data_xy.RData
load("data_xy.RData")

x
 [1] 23
y
 [1] 14

Save all variables

# save all variables (data objects) from the current R working session
save.image(file = "data_all.RData")
q()  # exit R

# load the saved R variables (same as above)
load("data_all.RData")

# list all variables present in R
ls()
 [1]  "x"  "y"


Save data content of a single variable (RDS)

While load() by default re-loads the variables into the global R environment (and potentially overwriting identical variable names, if not protected by defining a new environment), readRDS() can be used to better control individual variable names of imported data.

Use saveRDS to save a single variable and to re-load the content into any new variable name.


# save content of variable "x"
x = 23
saveRDS(x, "data_x.rds")

# load data (of former variable "x") into a new variable "a"
a = readRDS("data_x.rds")

ls()
  [1] "a"  "x"
a
 [1] 23
x
 [1] 23


Get list of saved R data files


# list all .RData files in current directory (path=".")
list.files(path = '.', pattern=".RData")
  [1] "data_all.RData" "data_xy.RData"