Debian Codegraph @

man/evals.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/evals.R
3 \name{evals}
4 \alias{evals}
5 \title{Evaluate and Process R Code}
6 \usage{
7 evals(
8 txt,
9 parse = evalsOptions("parse"),
10 cache = evalsOptions("cache"),
11 cache.mode = evalsOptions("cache.mode"),
12 cache.dir = evalsOptions("cache.dir"),
13 cache.time = evalsOptions("cache.time"),
14 cache.copy.images = evalsOptions("cache.copy.images"),
15 showInvisible = FALSE,
16 classes = evalsOptions("classes"),
17 hooks = evalsOptions("hooks"),
18 length = evalsOptions("length"),
19 output = evalsOptions("output"),
20 env = NULL,
21 graph.unify = evalsOptions("graph.unify"),
22 graph.name = evalsOptions("graph.name"),
23 graph.dir = evalsOptions("graph.dir"),
24 graph.output = evalsOptions("graph.output"),
25 width = evalsOptions("width"),
26 height = evalsOptions("height"),
27 res = evalsOptions("res"),
28 hi.res = evalsOptions("hi.res"),
29 hi.res.width = evalsOptions("hi.res.width"),
30 hi.res.height = 960 * (height/width),
31 hi.res.res = res * (hi.res.width/width),
32 graph.env = evalsOptions("graph.env"),
33 graph.recordplot = evalsOptions("graph.recordplot"),
34 graph.RDS = evalsOptions("graph.RDS"),
35 log = evalsOptions("log"),
36 ...
37 )
38 }
39 \arguments{
40 \item{txt}{a character vector containing R code. This could be a list/vector of lines of code or a simple string holding R code separated by \code{;} or \code{\\n}.}
41
42 \item{parse}{if \code{TRUE} the provided \code{txt} elements would be merged into one string and parsed to logical chunks. This is useful if you would want to get separate results of your code parts - not just the last returned value, but you are passing the whole script in one string. To manually lock lines to each other (e.g. calling a \code{plot} and on next line adding an \code{abline} or \code{text} to it), use a plus char (\code{+}) at the beginning of each line which should be evaluated with the previous one(s). If set to \code{FALSE}, \code{evals} would not try to parse R code, it would get evaluated in separate runs - as provided. Please see examples below.}
43
44 \item{cache}{caching the result of R calls if set to \code{TRUE}. Please note the caching would not work if \code{parse} set to \code{FALSE} or syntax error is to be found.}
45
46 \item{cache.mode}{cached results could be stored in an \code{environment} in \emph{current} R session or let it be permanent on \code{disk}.}
47
48 \item{cache.dir}{path to a directory holding cache files if \code{cache.mode} set to \code{disk}. Default to \code{.cache} in current working directory.}
49
50 \item{cache.time}{number of seconds to limit caching based on \code{proc.time}. If set to \code{0}, all R commands, if set to \code{Inf}, none is cached (despite the \code{cache} parameter).}
51
52 \item{cache.copy.images}{copy images to new file names if an image is returned from the \emph{disk} cache? If set to \code{FALSE} (default), the cached path would be returned.}
53
54 \item{showInvisible}{return \code{invisible} results?}
55
56 \item{classes}{a vector or list of classes which should be returned. If set to \code{NULL} (by default) all R objects will be returned.}
57
58 \item{hooks}{list of hooks to be run for given classes in the form of \code{list(class = fn)}. If you would also specify some parameters of the function, a list should be provided in the form of \code{list(fn, param1, param2=NULL)} etc. So the hooks would become \code{list(class1=list(fn, param1, param2=NULL), ...)}. See example below. A default hook can be specified too by setting the class to \code{'default'}. This can be handy if you do not want to define separate methods/functions to each possible class, but automatically apply the default hook to all classes not mentioned in the list. You may also specify only one element in the list like: \code{hooks=list('default' = pander_return)}. Please note, that nor error/warning messages, nor stdout is captured (so: updated) while running hooks!}
59
60 \item{length}{any R object exceeding the specified length will not be returned. The default value (\code{Inf}) does not filter out any R objects.}
61
62 \item{output}{a character vector of required returned values. This might be useful if you are only interested in the \code{result}, and do not want to save/see e.g. \code{messages} or \code{print}ed \code{output}. See examples below.}
63
64 \item{env}{environment where evaluation takes place. If not set (by default), a new temporary environment is created.}
65
66 \item{graph.unify}{should \code{evals} try to unify the style of (\code{base}, \code{lattice} and \code{ggplot2}) plots? If set to \code{TRUE}, some \code{panderOptions()} would apply. By default this is disabled not to freak out useRs :)}
67
68 \item{graph.name}{set the file name of saved plots which is \code{\link{tempfile}} by default. A simple character string might be provided where \code{\%d} would be replaced by the index of the generating \code{txt} source, \code{\%n} with an incremented integer in \code{graph.dir} with similar file names and \code{\%t} by some unique random characters. While running in \code{\link{Pandoc.brew}} other indices could be triggered like \code{\%i} and \code{\%I}.}
69
70 \item{graph.dir}{path to a directory where to place generated images. If the directory does not exist, \code{evals} try to create that. Default set to \code{plots} in current working directory.}
71
72 \item{graph.output}{set the required file format of saved plots. Currently it could be any of \code{grDevices}': \code{png}, \code{bmp}, \code{jpeg}, \code{jpg}, \code{tiff}, \code{svg} or \code{pdf}.}
73
74 \item{width}{width of generated plot in pixels for even vector formats}
75
76 \item{height}{height of generated plot in pixels for even vector formats}
77
78 \item{res}{nominal resolution in \code{ppi}. The height and width of vector images will be calculated based in this.}
79
80 \item{hi.res}{generate high resolution plots also? If set to \code{TRUE}, each R code parts resulting an image would be run twice.}
81
82 \item{hi.res.width}{width of generated high resolution plot in pixels for even vector formats}
83
84 \item{hi.res.height}{height of generated high resolution plot in pixels for even vector formats. This value can be left blank to be automatically calculated to match original plot aspect ratio.}
85
86 \item{hi.res.res}{nominal resolution of high resolution plot in ppi. The height and width of vector plots will be calculated based in this. This value can be left blank to be automatically calculated to fit original plot scales.}
87
88 \item{graph.env}{save the environments in which plots were generated to distinct files (based on \code{graph.name}) with \code{env} extension?}
89
90 \item{graph.recordplot}{save the plot via \code{recordPlot} to distinct files (based on \code{graph.name}) with \code{recodplot} extension?}
91
92 \item{graph.RDS}{save the raw R object returned (usually with \code{lattice} or \code{ggplot2}) while generating the plots to distinct files (based on \code{graph.name}) with \code{RDS} extension?}
93
94 \item{log}{an optionally passed \emph{namespace} for \pkg{logger} to record all info, trace, debug and error messages.}
95
96 \item{...}{optional parameters passed to graphics device (e.g. \code{bg}, \code{pointsize} etc.)}
97 }
98 \value{
99 a list of parsed elements each containing: \code{src} (the command run), \code{result} (R object: \code{NULL} if nothing returned, path to image file if a plot was generated), \code{print}ed \code{output}, \code{type} (class of returned object if any), informative/wawrning and error messages (if any returned by the command run, otherwise set to \code{NULL}) and possible \code{stdout}t value. See Details above.
100 }
101 \description{
102 This function takes either a vector/list of \emph{strings} with actual R code, which it to be \code{parse}d to separate elements. Each list element is \code{eval}uated in a special environment, and a detailed list of results is returned for each logical part of the R code: a character value with R code, resulting R object, printed output, class of resulting R object, possible informative/warning/error messages and anything written to \code{stdout}. If a graph is plotted in the given text, the returned object is a string specifying the path to the saved file. Please see Details below.
103 If \code{parse} option set to \code{FALSE}, then the returned list's length equals to the length of the \code{parse}d input - as each string is evaluated as separate R code in the same environment. If a nested list of R code or a concatenated string (separated by \code{\\n} or \code{;}) is provided like \code{list(c('runif(1)', 'runif(1)'))} with \code{parse=FALSE}, then everything is \code{eval}ed at one run so the length of returned list equals to one or the length of the provided nested list. See examples below.
104 }
105 \details{
106 As \code{\link{evals}} tries to grab the plots internally, pleas do not run commands that set graphic device or \code{dev.off}. E.g. running \code{evals(c('png("/tmp/x.png")', 'plot(1:10)', 'dev.off()'))} would fail. \code{print}ing of \code{lattice} and \code{ggplot2} objects is not needed, \code{evals} would deal with that automatically.
107
108 The generated image file(s) of the plots can be fine-tuned by some specific options, please check out \code{graph.output}, \code{width}, \code{height}, \code{res}, \code{hi.res}, \code{hi.res.width}, \code{hi.res.height} and \code{hi.res.res} parameters. Most of these options are better not to touch, see details of parameters below.
109
110 Returned result values: list with the following elements
111 \itemize{
112 \item \emph{src} - character vector of specified R code.
113 \item \emph{result} - result of evaluation. \code{NULL} if nothing is returned. If any R code returned an R object while evaluating then the \emph{last} R object will be returned as a raw R object. If a graph is plotted in the given text, the returned object is a string (with \code{class} set to \code{image}) specifying the path to the saved image file. If graphic device was touched, then no other R objects will be returned.
114 \item \emph{output} - character vector of printed version (\code{capture.output}) of \code{result}
115 \item \emph{type} - class of generated output. 'NULL' if nothing is returned, 'error' if some error occurred.
116 \item \emph{msg} - possible messages grabbed while evaluating specified R code with the following structure:
117 \itemize{
118 \item \emph{messages} - character vector of possible diagnostic message(s)
119 \item \emph{warnings} - character vector of possible warning message(s)
120 \item \emph{errors} - character vector of possible error message(s)
121 }
122 \item \emph{stdout} - character vector of possibly printed texts to standard output (console)
123 }
124
125 By default \code{evals} tries to \emph{cache} results. This means that if evaluation of some R commands take too much time (specified in \code{cache.time} parameter), then \code{evals} would save the results in a file and return from there on next exact R code's evaluation. This caching algorithm tries to be smart as checks not only the passed R sources, but all variables inside that and saves the hash of those.
126
127 Technical details of the caching algorithm:
128 \itemize{
129 \item Each passed R chunk is \code{parse}d to single commands.
130 \item Each parsed command's part (let it be a function, variable, constant etc.) \code{eval}uated (as a \code{name}) separately to a \code{list}. This list describes the unique structure and the content of the passed R commands, and has some IMHO really great benefits (see examples below).
131 \item A hash if computed to each list element and cached too in \code{pander}'s local environments. This is useful if you are using large data frames, just imagine: the caching algorithm would have to compute the hash for the same data frame each time it's touched! This way the hash is recomputed only if the R object with the given name is changed.
132 \item The list is \code{serialize}d and an \code{SHA-1} hash is computed for that - which is unique and there is no real risk of collision.
133 \item If \code{evals} can find the cached results in a file named to the computed hash, then it is returned on the spot.
134 \item Otherwise the call is evaluated and the results are optionally saved to cache (e.g. if \code{cache} is active, if the \code{proc.time()} of the evaluation is higher then it is defined in \code{cache.time} etc.).
135 }
136
137 This is a quite secure way of caching, but if you would encounter any issues, just set \code{cache} to \code{FALSE} or tweak other cache parameters. While setting \code{cache.dir}, please do think about what you are doing and move your \code{graph.dir} accordingly, as \code{evals} might result in returning an image file path which is not found any more on your file system!
138
139 Also, if you have generated a plot and rendered that to e.g. \code{png} before and later try to get e.g. \code{pdf} - it would fail with \code{cache} on. Similarly you cannot render a high resolution image of a cached image, but you have to (temporary) disable caching.
140
141 The default \code{evals} options could be set globally with \code{\link{evalsOptions}}, e.g. to switch off the cache just run \code{evalsOptions('cache', FALSE)}.
142
143 Please check the examples carefully below to get a detailed overview of \code{\link{evals}}.
144 }
145 \examples{
146 \dontrun{
147 # parsing several lines of R code
148 txt <- readLines(textConnection('x <- rnorm(100)
149 runif(10)
150 warning('Lorem ipsum foo-bar-foo!')
151 plot(1:10)
152 qplot(rating, data = movies, geom = 'histogram')
153 y <- round(runif(100))
154 cor.test(x, y)
155 crl <- cor.test(runif(10), runif(10))
156 table(mtcars$am, mtcars$cyl)
157 ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))'))
158 evals(txt)
159
160 ## parsing a list of commands
161 txt <- list('df <- mtcars',
162 c('plot(mtcars$hp, pch = 19)','text(mtcars$hp, label = rownames(mtcars), pos = 4)'),
163 'ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))')
164 evals(txt)
165
166 ## the same commands in one string but also evaluating the `plot` with `text`
167 ## (note the leading '+' on the beginning of `text...` line)
168 txt <- 'df <- mtcars
169 plot(mtcars$hp, pch = 19)
170 +text(mtcars$hp, label = rownames(mtcars), pos = 4)
171 ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))'
172 evals(txt)
173 ## but it would fail without parsing
174 evals(txt, parse = FALSE)
175
176 ## handling messages
177 evals('message(20)')
178 evals('message(20);message(20)', parse = FALSE)
179
180 ## adding a caption to a plot
181 evals('set.caption("FOO"); plot(1:10)')
182 ## `plot` is started with a `+` to eval the codes in the same chunk
183 ## (no extra chunk with NULL result)
184 evals('set.caption("FOO"); +plot(1:10)')
185
186 ## handling warnings
187 evals('chisq.test(mtcars$gear, mtcars$hp)')
188 evals(list(c('chisq.test(mtcars$gear, mtcars$am)', 'pi',
189 'chisq.test(mtcars$gear, mtcars$hp)')), parse = FALSE)
190 evals(c('chisq.test(mtcars$gear, mtcars$am)',
191 'pi',
192 'chisq.test(mtcars$gear, mtcars$hp)'))
193
194 ## handling errors
195 evals('runiff(20)')
196 evals('Old MacDonald had a farm\\\\dots')
197 evals('## Some comment')
198 evals(c('runiff(20)', 'Old MacDonald had a farm?'))
199 evals(list(c('runiff(20)', 'Old MacDonald had a farm?')), parse = FALSE)
200 evals(c('mean(1:10)', 'no.R.function()'))
201 evals(list(c('mean(1:10)', 'no.R.function()')), parse = FALSE)
202 evals(c('no.R.object', 'no.R.function()', 'very.mixed.up(stuff)'))
203 evals(list(c('no.R.object', 'no.R.function()', 'very.mixed.up(stuff)')), parse = FALSE)
204 evals(c('no.R.object', 'Old MacDonald had a farm\\\\dots', 'pi'))
205 evals('no.R.object;Old MacDonald had a farm\\\\dots;pi', parse = FALSE)
206 evals(list(c('no.R.object', 'Old MacDonald had a farm\\\\dots', 'pi')), parse = FALSE)
207
208 ## graph options
209 evals('plot(1:10)')
210 evals('plot(1:10);plot(2:20)')
211 evals('plot(1:10)', graph.output = 'jpg')
212 evals('plot(1:10)', height = 800)
213 evals('plot(1:10)', height = 800, hi.res = TRUE)
214 evals('plot(1:10)', graph.output = 'pdf', hi.res = TRUE)
215 evals('plot(1:10)', res = 30)
216 evals('plot(1:10)', graph.name = 'myplot')
217 evals(list('plot(1:10)', 'plot(2:20)'), graph.name = 'myplots-\%d')
218 evals('plot(1:10)', graph.env = TRUE)
219 evals('x <- runif(100);plot(x)', graph.env = TRUE)
220 evals(c('plot(1:10)', 'plot(2:20)'), graph.env = TRUE)
221 evals(c('x <- runif(100)', 'plot(x)','y <- runif(100)', 'plot(y)'), graph.env = TRUE)
222 evals(list(
223 c('x <- runif(100)', 'plot(x)'),
224 c('y <- runif(100)', 'plot(y)')),
225 graph.env = TRUE, parse = FALSE)
226 evals('plot(1:10)', graph.recordplot = TRUE)
227 ## unprinted lattice plot
228 evals('histogram(mtcars$hp)', graph.recordplot = TRUE)
229
230 ## caching
231 system.time(evals('plot(mtcars)'))
232 system.time(evals('plot(mtcars)')) # running again to see the speed-up :)
233 system.time(evals('plot(mtcars)', cache = FALSE)) # cache disabled
234
235 ## caching mechanism does check what's inside a variable:
236 x <- mtcars
237 evals('plot(x)')
238 x <- cbind(mtcars, mtcars)
239 evals('plot(x)')
240 x <- mtcars
241 system.time(evals('plot(x)'))
242
243 ## stress your CPU - only once!
244 evals('x <- sapply(rep(mtcars$hp, 1e3), mean)') # run it again!
245
246 ## play with cache
247 require(lattice)
248 evals('histogram(rep(mtcars$hp, 1e5))')
249 ## nor run the below call
250 ## that would return the cached version of the above call :)
251 f <- histogram
252 g <- rep
253 A <- mtcars$hp
254 B <- 1e5
255 evals('f(g(A, B))')#'
256
257 ## or switch off cache globally:
258 evalsOptions('cache', FALSE)
259 ## and switch on later
260 evalsOptions('cache', TRUE)
261
262 ## evaluate assignments inside call to evals
263 ## changes to environments are cached properly and retreived
264 evalsOptions('cache.time', 0)
265 x <- 2
266 evals('x <- x^2')[[1]]$result
267 evals('x <- x^2; x + 1')[[2]]$result
268 evalsOptions('cache.time', 0.1)
269
270 ## returning only a few classes
271 txt <- readLines(textConnection('rnorm(100)
272 list(x = 10:1, y = 'Godzilla!')
273 c(1,2,3)
274 matrix(0,3,5)'))
275 evals(txt, classes = 'numeric')
276 evals(txt, classes = c('numeric', 'list'))
277
278 ## hooks
279 txt <- 'runif(1:4); matrix(runif(25), 5, 5); 1:5'
280 hooks <- list('numeric' = round, 'matrix' = pander_return)
281 evals(txt, hooks = hooks)
282 ## using pander's default hook
283 evals(txt, hooks = list('default' = pander_return))
284 evals('22/7', hooks = list('numeric' = round))
285 evals('matrix(runif(25), 5, 5)', hooks = list('matrix' = round))
286
287 ## setting default hook
288 evals(c('runif(10)', 'matrix(runif(9), 3, 3)'),
289 hooks = list('default'=round))
290 ## round all values except for matrices
291 evals(c('runif(10)', 'matrix(runif(9), 3, 3)'),
292 hooks = list(matrix = 'print', 'default' = round))
293
294 # advanced hooks
295 hooks <- list('numeric' = list(round, 2), 'matrix' = list(round, 1))
296 evals(txt, hooks = hooks)
297
298 # return only returned values
299 evals(txt, output = 'result')
300
301 # return only messages (for checking syntax errors etc.)
302 evals(txt, output = 'msg')
303
304 # check the length of returned values and do not return looong R objects
305 evals('runif(10)', length = 5)
306
307 # note the following will not be filtered!
308 evals('matrix(1,1,1)', length = 1)
309
310 # if you do not want to let such things be eval-ed in the middle of a string
311 # use it with other filters :)
312 evals('matrix(1,1,1)', length = 1, classes = 'numeric')
313
314 # hooks & filtering
315 evals('matrix(5,5,5)',
316 hooks = list('matrix' = pander_return),
317 output = 'result')
318
319 # eval-ing chunks in given environment
320 myenv <- new.env()
321 evals('x <- c(0,10)', env = myenv)
322 evals('mean(x)', env = myenv)
323 rm(myenv)
324 # note: if you had not specified 'myenv', the second 'evals' would have failed
325 evals('x <- c(0,10)')
326 evals('mean(x)')
327
328 # log
329 x <- evals('1:10', log = 'foo')
330 # trace log
331 evalsOptions('cache.time', 0)
332 x <- evals('1:10', log = 'foo')
333 x <- evals('1:10', log = 'foo')
334 # log to file
335 t <- tempfile()
336 log_appender(appender_file(t), name = 'evals')
337 x <- evals('1:10', log = 'evals')
338 readLines(t)
339 # permanent log for all events
340 evalsOptions('log', 'evals')
341 log_threshold(TRACE, 'evals')
342 evals('foo')
343 }
344 }
345 \seealso{
346 \code{\link{eval.msgs}} \code{\link{evalsOptions}}
347 }