root / src / R / cachecache.R @ master
Historique | Voir | Annoter | Télécharger (2,05 ko)
1 |
get_content = structure( function(## Get content from cached |
---|---|
2 |
### Access to the cached content of a file via the global variable CACHE_CACHE. Load content in CACHE_CACHE if needed. |
3 |
filename, ##<< The path to the file that contain dataset |
4 |
class=NULL, ##<< The class of dataset |
5 |
# FORCE_RELOAD=FALSE, ##<< Force cachecache to reload the value |
6 |
... ##<< Parameters that will be passed to my_read |
7 |
) { |
8 |
if (inherits(try(CACHE_CACHE,TRUE), "try-error") || is.null(CACHE_CACHE)) { |
9 |
CACHE_CACHE <<- list() |
10 |
} |
11 |
obj = list(filename=filename) |
12 |
class(obj) = class |
13 |
FORCE_RELOAD = FALSE |
14 |
if (is.null(CACHE_CACHE[[obj$filename]]) | FORCE_RELOAD) { |
15 |
print(paste("Loading file ",obj$filename, sep="")) |
16 |
tmp_content = my_read(obj, ...) |
17 |
print("affect it...") |
18 |
CACHE_CACHE[[obj$filename]] <<- tmp_content |
19 |
print("done.") |
20 |
} |
21 |
return(CACHE_CACHE[[obj$filename]]) |
22 |
### Returns the cached content of the current object. |
23 |
}, ex=function(){ |
24 |
# Create a dataframe |
25 |
df = data.frame(list(key1 = "value1", key2 = "value2"), stringsAsFactors=FALSE) |
26 |
df = rbind(df, list(key1 = "value1'", key2 = "value3'")) |
27 |
# Dump it into tmp file |
28 |
write.table(df, file="/tmp/tmp.dump.table.tmp") |
29 |
# Load it into cache using feature. |
30 |
# First time it will be load into cache |
31 |
print(get_content("/tmp/tmp.dump.table.tmp", "table", stringsAsFactors=FALSE)) |
32 |
# Second time not |
33 |
print(get_content("/tmp/tmp.dump.table.tmp", "table", stringsAsFactors=FALSE)) |
34 |
|
35 |
}) |
36 |
|
37 |
my_read = function( |
38 |
### Abstract my_read function. |
39 |
obj, ...) { |
40 |
UseMethod("my_read", obj) |
41 |
} |
42 |
|
43 |
my_read.default = function( |
44 |
### Default my_read function. |
45 |
obj, ...){ |
46 |
stop(paste("ERROR, my_read is not defined for any Objects (file ", obj$filename," )", sep="")) |
47 |
} |
48 |
|
49 |
my_read.table = function( |
50 |
### my_read function for table files. |
51 |
obj, ...){ |
52 |
if (rev(unlist(strsplit(obj$filename, ".", fixed=TRUE)))[1] == "gz") { |
53 |
return(read.table(file=gzfile(obj$filename), ...)) |
54 |
} else { |
55 |
return(read.table(file=obj$filename, ...)) |
56 |
} |
57 |
} |
58 |
|
59 |
my_read.csv = function( |
60 |
### my_read function for cvs files. |
61 |
obj, ...){ |
62 |
return(read.csv(file=obj$filename, ...)) |
63 |
} |