Automatically write readRDS () statements from saveRDS () statements

I often write statements saveRDS()after a lot of data extraction, and this prompts me to write immediately readRDS()for future, reproducible encoding, accessing .RDS files for faster loading in R. My manual process for creating statements readRDS()from typed statements is saveRDS()described below. How can this be improved? How can I write a macro / function to do this for me, in EMACSand / or R?

## I type these out:
saveRDS(dems,"./_00_data_original/dems.RDS")
saveRDS(meds,"./_00_data_original/meds.RDS")
saveRDS(anti,"./_00_data_original/anti.RDS")

## Then I rectangle kill (C-x-r-k) the file names and commas
## and rectangle yank (C-x-r-y) them on the left hand side
## note:  depends on filenames being equal lengths
dems,saveRDS("./_00_data_original/dems.RDS")
meds,saveRDS("./_00_data_original/meds.RDS")
anti,saveRDS("./_00_data_original/anti.RDS")

## then I Esc-Shift-5 to query replace ",saveRDS" with " <- readRDS"
dems <- readRDS("./_00_data_original/dems.RDS")
meds <- readRDS("./_00_data_original/meds.RDS")
anti <- readRDS("./_00_data_original/anti.RDS")
+4
source share
2 answers

Two ways that I can think of are to use a macro or multiple cursors.

Macro

, , - , .

saveRDS : :

  • insert "< - read"
  • 4 ()
  • 1 .

, . , , - "foo-bar baz", , , "bar", , forward-word forward-sexp .

C-x e e, . , , , 10 , C-u 10 C-x e

, , .

enter image description here

init name-last-kbd-macro insert-kbd-macro .

, , , .

https://github.com/magnars/multiple-cursors.el

enter image description here

+4

, - :

saveRead <- function(..., path, prefix = "", envir = .GlobalEnv) {
  dots <- substitute(list(...))[-1]
  objs <- sapply(dots, deparse)
  new_objs <- paste0(prefix, objs)
  paths <- file.path(path, paste0(objs, ".RDS"))
  invisible(lapply(seq_along(objs), function(x) {
    saveRDS(get(objs[x], envir = envir), file = paths[x])
    assign(new_objs[x], readRDS(paths[x]), envir = envir)
  }))
}

. tempdir, . , ( ) "test_". prefix "" ( ), .

a <- 1:2
b <- 3:4
ls()
# [1] "a"        "b"        "saveRead"

x <- tempdir()
list.files(x, ".RDS")
# character(0)

saveRead(a, b, path = x, prepend = "test_")
ls()
# [1] "a"        "b"        "saveRead" "test_a"   "test_b"   "x"       
list.files(x, ".RDS")
# [1] "a.RDS" "b.RDS"

, :

saveRead(dems, meds, anti, path = "./_00_data_original")
+1
source

All Articles