Debian Codegraph @

vignettes/svMisc.Rmd

raw
1 ---
2 title: "Miscellaneous Functions for 'SciViews::R'"
3 author: "Philippe Grosjean"
4 date: "`r Sys.Date()`"
5 output:
6 rmarkdown::html_vignette:
7 toc: true
8 toc_depth: 3
9 fig_caption: yes
10 vignette: >
11 %\VignetteIndexEntry{Miscellaneous Functions for 'SciViews::R'}
12 %\VignetteEngine{knitr::rmarkdown}
13 %\VignetteEncoding{UTF-8}
14 ---
15
16 ```{r setup, include=FALSE}
17 knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
18 library(svMisc)
19 ```
20
21 The {svMisc} package contains a large collection of functions that are useful in the context of (G)UI (Graphical) User Interface development, and also, of more general usage. Here is a series of functions you should look at.
22
23 ## Help
24
25 In R, you access man pages for the various R objects with `help(topic)`, or `?topic`. But, if `topic` is not found, these function do not return a very useful information. For instance, if you want to make a [Kalman filtering](https://doi.org/10.18637/jss.v039.i02) in R, you may be inclined to search for the topic `kalman`
26
27 ```{r}
28 ?kalman
29 ```
30
31 OK, it is suggested to use `??` to search the documentation for `kalman`. However, using `about()` instead immediately produces a more useful result:
32
33 ```{r}
34 library(svMisc)
35 about("kalman")
36 ```
37
38 ... and it also provides a list of potential man pages that could interest you. In case the topic is found, `about()` does the same as `help()` and shows the page (try with `about("log")`, for instance). If you still have not found what you are looking for, you could try to search on the Web by using `search_web()`.
39
40 You may also be interested by `is_help()` that indicates if an object is associated with a man page, and if it has a running example.
41
42 ## Packages
43
44 In R, the use of `library()` to load a **package** is very confusing. Given the number of questions raised about it, one could consider another function to load R packages in memory. `svMisc` proposes `package()`. That function loads one or several R packages as silently as possible and it returns `TRUE` only if **all** the packages are loaded. Otherwise, the list of missing packages is recorded^[The list of missing packages is written in a variable named `.packages_to_install` located in the `SciViews:TempEnv` environment], and one could simply issue `Install()` to install them. This is indeed a semi-automatic installation mechanisms for R packages. The UseR still masters the process, but it is more straightforward.
45
46 ## Analyses in batch and show progression
47
48 If you need to perform an analysis in batch mode, you may be happy with `batch()` and `progress()`. The first function runs a function sequentially on all items **allowing for an informative message in case of failure**. Also, `batch()` provides a mechanism to recover from the error, so that following items in the list are also analyzed. Indeed, if you use a simple `for()` loop or `applyXXX()` functions, the execution is stopped at the first error encountered. Imagine 500 items to process, and an error that appears at the second one... it leaves you 498 items unanalyzed! allows to continue to the next item.
49
50 The example shows a fake batch process of files, which fails randomly. Here is the function to run sequentially:
51
52 ```{r}
53 fake_process <- function(file) {
54 message("Processing ", file, "...")
55 flush.console()
56 Sys.sleep(0.5)
57 if (runif(1) > 0.7) {# Fail
58 warning("fake_process was unable to process ", file)
59 invisible(FALSE)
60 } else invisible(TRUE)
61 }
62 ```
63
64 The key aspect here is that you function, instead of using `stop()` must use `warning()` and return `FALSE`. Otherwise, in case of success, it should return `TRUE`. Then, calling your function on a series of objects is straightforward:
65
66 ```{r}
67 # Run it in batch mode on ten items
68 batch(paste0("file", 1:10), fake_process)
69 ```
70
71 In case an error occurred, the information is recorded i, `.last.batch`:
72
73 ```{r}
74 .last.batch
75 ```
76
77 The `items` and `ok` attributes are also available from that object for further inspection and action.
78
79 If you run `batch()` in R, you noted also the `progress()`ion message that appeared. Indeed the `progress()` function allows to display such a message, either as a text at the R console, or in a dialog box. There are many different forms, see the man page `?progress`. for instance, here is a progress bar in percent, stopped at 75% () you need to call `progress()` with a value higher than `max.value =` to dismiss it):
80
81 ```{r}
82 for (i in 0:75) {
83 progress(i, progress.bar = TRUE)
84 # Some process here...
85 }
86 ```
87
88 ## Subsettable functions
89
90 The `$` operator is not applicable on functions. It is not meaningful in that context. Yet, it may be convenient to use it in certain conditions. From the example of `?subsettable`:
91
92 ```{r}
93 foo <- structure(function(x, type = c("histogram", "boxplot"), ...) {
94 type <- match.arg(type, c("histogram", "boxplot"))
95 switch(type,
96 histogram = hist(x, ...),
97 boxplot = boxplot(x, ...),
98 stop("unknow type")
99 )
100 }, class = c("function", "subsettable_type"))
101 foo
102
103 # This function can be used as usual:
104 foo(rnorm(50), type = "histogram")
105 # ... but also this way:
106 foo$histogram(rnorm(50))
107 foo$boxplot(rnorm(50))
108 ```
109
110 ## Capture and parse R code
111
112 The `capture.output()` function from the 'utils' package can capture output usually send to the R console, but it does so in an imperfect way. If you want to capture output *exactly* as it would appear at the R console, you could use `capture_all()`:
113
114 ```{r}
115 captured <- capture_all(parse_text('1:2 + 1:3'), split = FALSE)
116 captured
117 ```
118
119 Only the prompt is changed to `:>`. You can use that content, or print it somewhere, for instance:
120
121 ```{r}
122 writeLines(captured)
123 ```
124
125 The `parse_text()` function parse one or more character strings exactly as if they were commands entered at the R prompt:
126
127 ```{r}
128 parse_text(c("1 + 1", "log(10)"))
129 ```
130
131 ... and for an incomplete expression:
132
133 ```{r}
134 parse_text("log(")
135 ```
136
137 The `source_clipboard()` source code directly from the clipboard. All these functions form the basis to simulate an R console in a different context (a console widget in your own GUI). You can combine this with `to_rjson()`/`eval_rjson` to encode and decode R objects on both sides of a pipeline between the R process and your GUI.
138
139 ## Encode/decode R objects in Rjson
140
141 Rjson is a version of [JSON](https://www.json.org/json-en.html) that allows to encore and decode rapidly almost all R objects. From the example at `?to_rjson`:
142
143 ```{r}
144 # A complex R object
145 # Note: we round doubles to 14 digits because precision is lost in the process
146 obj <- structure(list(
147 a = as.double(c(1:5, 6)),
148 LETTERS,
149 c = c(c1 = 4.5, c2 = 7.8, c3 = Inf, c4 = -Inf, NA, c6 = NaN),
150 c(TRUE, FALSE, NA),
151 e = factor(c("a", "b", "a")),
152 f = 'this is a "string" with quote',
153 g = matrix(round(rnorm(4), 14), ncol = 2),
154 `h&$@` = list(x = 1:3, y = round(rnorm(3), 14),
155 fact = factor(c("b", "a", "b"))),
156 i = Sys.Date(),
157 j = list(1:5, y = "another item")),
158 comment = "My comment",
159 anAttrib = 1:10,
160 anotherAttrib = list(TRUE, y = 1:4))
161
162 # Convert to RJSON
163 (rjson1 <- to_rjson(obj, attributes = TRUE))
164 # Get back an R object from Rjson
165 (obj2 <- eval_rjson(rjson1))
166 # Is it identical to obj?
167 identical(obj, obj2)
168 ```
169
170 ## Get system file or directory
171
172 There are several different functions in R to access system files, or files inside R packages: `R.home()`, `system.file()`, `Sys.which()`, `tempdir()`. The `system_dir()` and `system_file()` functions centralize their functionalities. For instance:
173
174 - Get the temporary directory used by this R process
175
176 ```{r}
177 system_dir("temp")
178 ```
179
180 - Get the system temporary directory
181
182 ```{r}
183 system_dir("sysTemp")
184 ```
185
186 - Get the home directory of the current user
187
188 ```{r}
189 system_dir("user")
190 ```
191
192 - Get the R home directory
193
194 ```{r}
195 system_dir("home")
196 ```
197
198 - Get the path to an executable
199
200 ```{r}
201 system_dir("zip", exec = TRUE)
202 ```
203
204 - Get the file of that executable
205
206 ```{r}
207 system_file("zip", exec = TRUE)
208 ```
209
210
211 - Get the root directory of a package
212
213 ```{r}
214 system_dir(package = "stats")
215 ```
216
217 - Get a file from a package
218
219 ```{r}
220 system_file("help", "AnIndex", package = "splines")
221 ```
222
223 There are other possibilities. See `?system_dir`. You may also be interested by `file_edit()` that allows to create and edit a text file from a template.
224
225 ## Various information functions
226
227 - `compare_r_version()` conveniently compares the current R version with a specified one. It returns 1 if it is newer, 0, if it is equal and -1 if it is older.
228
229 ```{r}
230 compare_r_version("5.6.0") # Probably older
231 ```
232
233 ```{r}
234 compare_r_version("0.6.0") # Probably newer
235 ```
236
237 - Check the environment:
238
239 ```{r}
240 is_win() # Windows?
241 is_mac() # MacOS?
242 is_rgui() # Is it RGui under Windows?
243 is_sdi() # Is RGui run in SDI mode (separate windows)?
244 is_rstudio() # Is it RStudio?
245 is_rstudio_desktop() # RStudio desktop?
246 is_rstudio_server() # RStudio server?
247 is_jgr() # Is R running under JGR?
248 ```
249
250 ## Miscellaneous
251
252 - Make sure a vector is of a defined mode and length (possibly by applying recycling rule) using `def()`:
253
254 ```{r}
255 def(0:2, mode = "logical", length.out = 5) # logical, size 5
256 ```
257
258 - Get a nicely formatted `args()` (see `?arg_tips` for other functions to get short textual information about functions):
259
260 ```{r}
261 args_tip("ls")
262 ```
263
264 - Get the name of an (unused) temporary variable:
265
266 ```{r}
267 temp_var("my_var")
268 ```
269
270 - Manage a temporary environment attached to the search path using `TempEnv()` and the `temp_XXX()` functions. The **temporary_environment** vignette gives more details on this series of functions.
271
272 ```{r}
273 search()
274 # Assign a variable in a temporary environment
275 assign_temp("my_var", 1:5)
276 # The environment is named SciViews:TempEnv
277 search()
278 # Get the variable
279 get_temp("my_var")
280 # List variables in the temporary environment
281 ls(envir = TempEnv())
282 # Delete the variable
283 rm_temp("my_var")
284 ```
285