-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsave_objects.R
More file actions
47 lines (41 loc) · 1.61 KB
/
save_objects.R
File metadata and controls
47 lines (41 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
save_objects <- function(objects, path, rds = FALSE) {
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This function saves R objects with either `dput` or 'saveRDS'.
#
# dput saves object code a text file
# saveRDS saves objects in rds format, which is a compressed format - saves and reads back into R much faster than a text file.
#
# Inputs~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# objects - character vector of objects you wish to save
#
# path - character vector of where you want to save objects
#
# rds - logical; if set to TRUE the objects will be saved in rds format
# default is FALSE for backwards compatablity.
#
# Outputs~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# All objects are saved as "objects.txt" or "objects.rds"
#
# Example~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# iris <- iris # bringing into pos = 1
# save_objects(objects = "iris", path = "Objects", rds = TRUE)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (!all(objects %in% ls(pos = 1))) {
stop(paste0(
"These objects:\n",
paste(setdiff(objects, ls(pos = 1)), collapse = "\n"),
"\nare not in your workspace, hoser!!!"
))
}
empty <- sapply(objects, function(obj) {
x <- get(obj)
if (!is.null(attr(x = x, which = "problems"))) {
attr(x = x, which = "problems") <- NULL
} # resolves issue with readr::read_csv not playing nicely with dget if attr-problems exist
if (rds == FALSE) {
dput(x, paste0(path, "/", obj, ".txt"))
} else {
saveRDS(x, paste0(path, "/", obj, ".rds"))
}
})
}