Compile-time action in R -
suppose have file foo.r , list of regular expressions in rex.txt. if put
rex <- paste(read.table("rex.txt", stringsasfactors=false)[[1]],collapse="|") into foo.r, variable rex initialized correctly when load foo.r using library(). same happens when compile foo.r foo.rc , load latter, good.
what want, however, literal value of variable rex included in foo.rc (when call cmpfile), i.e., when foo.rc loaded, variable rex initialised whatever in rex.txt @ compilation time, similar emacs lisp eval-when-compile (this way don't have copy rex.txt server run foo.rc).
is possible?
you can modify foo.r just before compilation, shown below.
test data:
text <- ' dosomething() rex <- paste(read.table("rex.txt", stringsasfactors=false)[[1]],collapse="|") dootherstuff() ' writelines(text,"foo.r") code:
foo <- readlines("foo.r") pattern <- "^rex\\s*<-.*$" eval(parse(text=grep(pattern, foo, value=true))[[1]]) newtext <- gsub(pattern, paste("rex <-",deparse(rex)), foo) writelines(newtext,"foo.r") note eval() execute line rex <- ... create object in global environment, deparse() can find it. i'm assuming have 1 line matching pattern used.
Comments
Post a Comment