Statistiques
| Branche: | Révision :

root / src / R / cachecache.R @ 5e1de699

Historique | Voir | Annoter | Télécharger (2,03 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
  if (is.null(CACHE_CACHE[[obj$filename]]) | FORCE_RELOAD) {
14
    print(paste("Loading file ",obj$filename, sep=""))
15
		tmp_content = my_read(obj, ...)
16
    print("affect it...")
17
    CACHE_CACHE[[obj$filename]] <<- tmp_content
18
    print("done.")
19
  }  
20
  return(CACHE_CACHE[[obj$filename]])
21
### Returns the cached content of the current object. 
22
}, ex=function(){
23
	# Create a dataframe
24
	df = data.frame(list(key1 = "value1", key2 = "value2"), stringsAsFactors=FALSE)
25
	df = rbind(df, list(key1 = "value1'", key2 = "value3'"))
26
	# Dump it into tmp file
27
	write.table(df, file="/tmp/tmp.dump.table.tmp")
28
	# Load it into cache using feature.
29
	# First time it will be load into cache
30
	print(get_content("/tmp/tmp.dump.table.tmp", "table", stringsAsFactors=FALSE))
31
	# Second time not
32
	print(get_content("/tmp/tmp.dump.table.tmp", "table", stringsAsFactors=FALSE))
33
	
34
})
35
	
36
my_read = function(
37
### Abstract my_read function.	
38
	obj, ...) {
39
  UseMethod("my_read", obj)
40
}
41
	
42
my_read.default = function(
43
### Default my_read function.	
44
	obj, ...){
45
  stop(paste("ERROR, my_read is not defined for any Objects (file ", obj$filename," )", sep=""))			
46
}
47

    
48
my_read.table = function(
49
### my_read function for table files.	
50
	obj, ...){
51
	if (rev(unlist(strsplit(obj$filename, ".", fixed=TRUE)))[1] == "gz") {
52
	  return(read.table(file=gzfile(obj$filename), ...))			
53
	} else { 
54
	  return(read.table(file=obj$filename, ...))
55
	}
56
}	
57

    
58
my_read.cvs = function(
59
### my_read function for cvs files.	
60
	obj, ...){
61
  return(read.csv(file=obj$filename, ...))
62
}