]> code.communitydata.science - ml_measurement_error_public.git/blob - simulations/RemembR/R/RemembeR.R
bugfix in example.
[ml_measurement_error_public.git] / simulations / RemembR / R / RemembeR.R
1 library(filelock)
2
3 init.remember <- function(){
4
5     if(exists("r") == FALSE){
6         if(file.exists(remember.file)){
7             if(!exists("remember.file.lock"))
8                 init.file.lock()
9             lck  <- lock(remember.file.lock, exclusive = FALSE)
10             r <<- readRDS(remember.file)
11             unlock(lck)
12         } else {
13             r <<- list()
14         }
15     }
16
17 }
18
19 remember.file <<- "remembr.RDS"
20 init.file.lock <- function(){
21     remember.file.lock <<- paste0(remember.file,"_LOCK")
22 }
23
24 remember.prefix  <<- ""
25
26
27 change.remember.file <- function(file,clear=FALSE){
28     if(!clear){
29         remember.file <<- file
30         init.file.lock()
31         save.remember()
32     } else {
33         remember.file <<- file
34         rm(r,pos=globalenv())
35         init.remember()
36     }
37 }
38 set.remember.prefix <- function(prefix){
39     remember.prefix <<- prefix
40 }
41
42 load.if.exists <- function(){
43     if(file.exists(remember.file)){
44         if(!exists("remember.file.lock"))
45             init.file.lock()
46         lck  <- lock(remember.file.lock, exclusive = FALSE)
47         r <<- readRDS(remember.file)
48         unlock(lck)
49     } else {
50         r <<- list()
51     }
52 }
53
54 remember <- function(var,name,lock=T){
55
56     init.remember()
57
58     load.if.exists()
59
60     if(remember.prefix == ""){
61         r[[name]] <<- var
62     } else {
63         if(is.null(r[[remember.prefix]])){
64             r[[remember.prefix]]  <<- list()
65         }
66         r[[remember.prefix]][[name]]  <<- var
67     }
68
69     save.remember()
70 }
71
72 save.remember <- function(lock=T){
73     if(!exists("remember.file.lock"))
74         init.file.lock()
75     
76     lck  <- lock(remember.file.lock, exclusive=TRUE)
77     saveRDS(r,file=remember.file)
78     unlock(lck)
79 }
80 init.remember()

Community Data Science Collective || Want to submit a patch?