Statistiques
| Branche: | Révision :

root / src / R / cachecache.R @ c68acc42

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

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

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