File: evals.Rd

package info (click to toggle)
r-cran-pander 0.6.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,804 kB
  • sloc: javascript: 301; cpp: 145; lisp: 94; makefile: 21
file content (337 lines) | stat: -rw-r--r-- 19,853 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/evals.R
\name{evals}
\alias{evals}
\title{Evaluate and Process R Code}
\usage{
evals(txt, parse = evalsOptions("parse"),
  cache = evalsOptions("cache"),
  cache.mode = evalsOptions("cache.mode"),
  cache.dir = evalsOptions("cache.dir"),
  cache.time = evalsOptions("cache.time"),
  cache.copy.images = evalsOptions("cache.copy.images"),
  showInvisible = FALSE, classes = evalsOptions("classes"),
  hooks = evalsOptions("hooks"), length = evalsOptions("length"),
  output = evalsOptions("output"), env = NULL,
  graph.unify = evalsOptions("graph.unify"),
  graph.name = evalsOptions("graph.name"),
  graph.dir = evalsOptions("graph.dir"),
  graph.output = evalsOptions("graph.output"),
  width = evalsOptions("width"), height = evalsOptions("height"),
  res = evalsOptions("res"), hi.res = evalsOptions("hi.res"),
  hi.res.width = evalsOptions("hi.res.width"), hi.res.height = 960 *
  (height/width), hi.res.res = res * (hi.res.width/width),
  graph.env = evalsOptions("graph.env"),
  graph.recordplot = evalsOptions("graph.recordplot"),
  graph.RDS = evalsOptions("graph.RDS"), log = evalsOptions("log"),
  ...)
}
\arguments{
\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}.}

\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.}

\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.}

\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}.}

\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.}

\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).}

\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.}

\item{showInvisible}{return \code{invisible} results?}

\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.}

\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!}

\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.}

\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.}

\item{env}{environment where evaluation takes place. If not set (by default), a new temporary environment is created.}

\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 :)}

\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}.}

\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.}

\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}.}

\item{width}{width of generated plot in pixels for even vector formats}

\item{height}{height of generated plot in pixels for even vector formats}

\item{res}{nominal resolution in \code{ppi}. The height and width of vector images will be calculated based in this.}

\item{hi.res}{generate high resolution plots also? If set to \code{TRUE}, each R code parts resulting an image would be run twice.}

\item{hi.res.width}{width of generated high resolution plot in pixels for even vector formats}

\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.}

\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.}

\item{graph.env}{save the environments in which plots were generated to distinct files (based on \code{graph.name}) with \code{env} extension?}

\item{graph.recordplot}{save the plot via \code{recordPlot} to distinct files (based on \code{graph.name}) with \code{recodplot} extension?}

\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?}

\item{log}{an optionally passed \emph{logger name} from \pkg{futile.logger} to record all info, trace, debug and error messages. Logging to the console can be done by specifying e.g. \code{flog.namespace()}, and log to a file by previously calling \code{flog.appender} and \code{appender.file} on the given \emph{logger name}.}

\item{...}{optional parameters passed to graphics device (e.g. \code{bg}, \code{pointsize} etc.)}
}
\value{
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.
}
\description{
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.
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.
}
\details{
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.

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.

Returned result values: list with the following elements
\itemize{
    \item \emph{src} - character vector of specified R code.
    \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.
     \item \emph{output} - character vector of printed version (\code{capture.output}) of \code{result}
    \item \emph{type} - class of generated output. 'NULL' if nothing is returned, 'error' if some error occurred.
    \item \emph{msg} - possible messages grabbed while evaluating specified R code with the following structure:
    \itemize{
        \item \emph{messages} - character vector of possible diagnostic message(s)
        \item \emph{warnings} - character vector of possible warning message(s)
        \item \emph{errors} - character vector of possible error message(s)
    }
    \item \emph{stdout} - character vector of possibly printed texts to standard output (console)
}

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.

Technical details of the caching algorithm:
\itemize{
     \item Each passed R chunk is \code{parse}d to single commands.
     \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).
     \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.
     \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.
     \item If \code{evals} can find the cached results in a file named to the computed hash, then it is returned on the spot.
     \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.).
}

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!

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.

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)}.

Please check the examples carefully below to get a detailed overview of \code{\link{evals}}.
}
\examples{
\dontrun{
# parsing several lines of R code
txt <- readLines(textConnection('x <- rnorm(100)
  runif(10)
  warning('Lorem ipsum foo-bar-foo!')
  plot(1:10)
  qplot(rating, data = movies, geom = 'histogram')
  y <- round(runif(100))
  cor.test(x, y)
  crl <- cor.test(runif(10), runif(10))
  table(mtcars$am, mtcars$cyl)
  ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))'))
evals(txt)

## parsing a list of commands
txt <- list('df <- mtcars',
 c('plot(mtcars$hp, pch = 19)','text(mtcars$hp, label = rownames(mtcars), pos = 4)'),
 'ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))')
evals(txt)

## the same commands in one string but also evaluating the `plot` with `text`
## (note the leading '+' on the beginning of `text...` line)
txt <- 'df <- mtcars
 plot(mtcars$hp, pch = 19)
 +text(mtcars$hp, label = rownames(mtcars), pos = 4)
 ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))'
evals(txt)
## but it would fail without parsing
evals(txt, parse = FALSE)

## handling messages
evals('message(20)')
evals('message(20);message(20)', parse = FALSE)

## adding a caption to a plot
evals('set.caption("FOO"); plot(1:10)')
## `plot` is started with a `+` to eval the codes in the same chunk
## (no extra chunk with NULL result)
evals('set.caption("FOO"); +plot(1:10)')

## handling warnings
evals('chisq.test(mtcars$gear, mtcars$hp)')
evals(list(c('chisq.test(mtcars$gear, mtcars$am)', 'pi',
  'chisq.test(mtcars$gear, mtcars$hp)')), parse = FALSE)
evals(c('chisq.test(mtcars$gear, mtcars$am)',
  'pi',
  'chisq.test(mtcars$gear, mtcars$hp)'))

## handling errors
evals('runiff(20)')
evals('Old MacDonald had a farm\\\\dots')
evals('## Some comment')
evals(c('runiff(20)', 'Old MacDonald had a farm?'))
evals(list(c('runiff(20)', 'Old MacDonald had a farm?')), parse = FALSE)
evals(c('mean(1:10)', 'no.R.function()'))
evals(list(c('mean(1:10)', 'no.R.function()')), parse = FALSE)
evals(c('no.R.object', 'no.R.function()', 'very.mixed.up(stuff)'))
evals(list(c('no.R.object', 'no.R.function()', 'very.mixed.up(stuff)')), parse = FALSE)
evals(c('no.R.object', 'Old MacDonald had a farm\\\\dots', 'pi'))
evals('no.R.object;Old MacDonald had a farm\\\\dots;pi', parse = FALSE)
evals(list(c('no.R.object', 'Old MacDonald had a farm\\\\dots', 'pi')), parse = FALSE)

## graph options
evals('plot(1:10)')
evals('plot(1:10);plot(2:20)')
evals('plot(1:10)', graph.output = 'jpg')
evals('plot(1:10)', height = 800)
evals('plot(1:10)', height = 800, hi.res = TRUE)
evals('plot(1:10)', graph.output = 'pdf', hi.res = TRUE)
evals('plot(1:10)', res = 30)
evals('plot(1:10)', graph.name = 'myplot')
evals(list('plot(1:10)', 'plot(2:20)'), graph.name = 'myplots-\%d')
evals('plot(1:10)', graph.env = TRUE)
evals('x <- runif(100);plot(x)', graph.env = TRUE)
evals(c('plot(1:10)', 'plot(2:20)'), graph.env = TRUE)
evals(c('x <- runif(100)', 'plot(x)','y <- runif(100)', 'plot(y)'), graph.env = TRUE)
evals(list(
    c('x <- runif(100)', 'plot(x)'),
    c('y <- runif(100)', 'plot(y)')),
  graph.env = TRUE, parse = FALSE)
evals('plot(1:10)', graph.recordplot = TRUE)
## unprinted lattice plot
evals('histogram(mtcars$hp)', graph.recordplot = TRUE)

## caching
system.time(evals('plot(mtcars)'))
system.time(evals('plot(mtcars)'))                # running again to see the speed-up :)
system.time(evals('plot(mtcars)', cache = FALSE)) # cache disabled

## caching mechanism does check what's inside a variable:
x <- mtcars
evals('plot(x)')
x <- cbind(mtcars, mtcars)
evals('plot(x)')
x <- mtcars
system.time(evals('plot(x)'))

## stress your CPU - only once!
evals('x <- sapply(rep(mtcars$hp, 1e3), mean)')   # run it again!

## play with cache
require(lattice)
evals('histogram(rep(mtcars$hp, 1e5))')
## nor run the below call
## that would return the cached version of the above call :)
f <- histogram
g <- rep
A <- mtcars$hp
B <- 1e5
evals('f(g(A, B))')#'

## or switch off cache globally:
evalsOptions('cache', FALSE)
## and switch on later
evalsOptions('cache', TRUE)

## evaluate assignments inside call to evals
## changes to environments are cached properly and retreived
evalsOptions('cache.time', 0)
x <- 2
evals('x <- x^2')[[1]]$result
evals('x <- x^2; x + 1')[[2]]$result
evalsOptions('cache.time', 0.1)

## returning only a few classes
txt <- readLines(textConnection('rnorm(100)
  list(x = 10:1, y = 'Godzilla!')
  c(1,2,3)
   matrix(0,3,5)'))
evals(txt, classes = 'numeric')
evals(txt, classes = c('numeric', 'list'))

## hooks
txt <- 'runif(1:4); matrix(runif(25), 5, 5); 1:5'
hooks <- list('numeric' = round, 'matrix' = pander_return)
evals(txt, hooks = hooks)
## using pander's default hook
evals(txt, hooks = list('default' = pander_return))
evals('22/7', hooks = list('numeric' = round))
evals('matrix(runif(25), 5, 5)', hooks = list('matrix' = round))

## setting default hook
evals(c('runif(10)', 'matrix(runif(9), 3, 3)'),
  hooks = list('default'=round))
## round all values except for matrices
evals(c('runif(10)', 'matrix(runif(9), 3, 3)'),
  hooks = list(matrix = 'print', 'default' = round))

# advanced hooks
hooks <- list('numeric' = list(round, 2), 'matrix' = list(round, 1))
evals(txt, hooks = hooks)

# return only returned values
evals(txt, output = 'result')

# return only messages (for checking syntax errors etc.)
evals(txt, output = 'msg')

# check the length of returned values and do not return looong R objects
evals('runif(10)', length = 5)

# note the following will not be filtered!
evals('matrix(1,1,1)', length = 1)

# if you do not want to let such things be eval-ed in the middle of a string
# use it with other filters :)
evals('matrix(1,1,1)', length = 1, classes = 'numeric')

# hooks & filtering
evals('matrix(5,5,5)',
  hooks = list('matrix' = pander_return),
  output = 'result')

# eval-ing chunks in given environment
myenv <- new.env()
evals('x <- c(0,10)', env = myenv)
evals('mean(x)', env = myenv)
rm(myenv)
# note: if you had not specified 'myenv', the second 'evals' would have failed
evals('x <- c(0,10)')
evals('mean(x)')

# log
x <- evals('1:10', log = 'foo')
# trace log
evalsOptions('cache.time', 0)
x <- evals('1:10', log = 'foo')
x <- evals('1:10', log = 'foo')
# log to file
t <- tempfile()
flog.appender(appender.file(t), name = 'evals')
x <- evals('1:10', log = 'evals')
readLines(t)
# permanent log for all events
evalsOptions('log', 'evals')
flog.threshold(TRACE, 'evals')
evals('foo')
}
}
\seealso{
\code{\link{eval.msgs}} \code{\link{evalsOptions}}
}