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 )

- 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()) )

 [1] 23
 [1] 14
 [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

 [1] 23
 [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)

# list all variables present in R
 [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")

  [1] "a"  "x"
 [1] 23
 [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"