Debian Codegraph @

vignettes/xfun.Rmd

raw
1 ---
2 title: An Introduction to xfun
3 subtitle: A Collection of Miscellaneous Functions
4 author: "Yihui Xie"
5 date: "`{r} Sys.Date()`"
6 slug: xfun
7 githubEditURL: https://github.com/yihui/xfun/edit/main/vignettes/xfun.Rmd
8 output:
9 html:
10 meta:
11 css: ["@default", "@article"]
12 js: ["@sidenotes"]
13 options:
14 toc: true
15 number_sections: true
16 ---
17
18 <!--
19 %\VignetteIndexEntry{An Introduction to xfun}
20 %\VignetteEngine{litedown::vignette}
21 -->
22
23 ```{r setup, include=FALSE}
24 library(xfun)
25 litedown::reactor(attr.source = 'r')
26 ```
27
28 After writing about 20 R packages, I found I had accumulated several utility functions that I used across different packages, so I decided to extract them into a separate package. Previously I had been using the evil triple-colon `:::` to access these internal utility functions. Now with **xfun**, these functions have been exported, and more importantly, documented. It should be better to use them under the sun instead of in the dark.
29
30 This page shows examples of a subset of functions in this package. For a full list of functions, see the help page `help(package = 'xfun')`. The source package is available on GitHub: https://github.com/yihui/xfun.
31
32 ## No more partial matching for lists!
33
34 I have been bitten many times by partial matching in lists, e.g., when I want `x$a` but the element `a` does not exist in the list `x`, it returns the value `x$abc` if `abc` exists in `x`. A strict list is a list for which the partial matching of the `$` operator is disabled. The functions `xfun::strict_list()` and `xfun::as_strict_list()` are the equivalents to `base::list()` and `base::as.list()` respectively which always return as strict list, e.g.,
35
36 ```{r}
37 library(xfun)
38 (z = strict_list(aaa = "I am aaa", b = 1:5))
39 z$a # NULL (strict matching)
40 z$aaa # I am aaa
41 z$b
42 z$c = "you can create a new element"
43
44 z2 = unclass(z) # a normal list
45 z2$a # partial matching
46
47 z3 = as_strict_list(z2) # a strict list again
48 z3$a # NULL (strict matching) again!
49 ```
50
51 Similarly, the default partial matching in `attr()` can be annoying, too. The function `xfun::attr2()` is simply a shorthand of `attr(..., exact = TRUE)`.
52
53 I want it, or I do not want. There is no "I probably want".
54
55 ## Output character vectors for human eyes
56
57 When R prints a character vector, your eyes may be distracted by the indices like `[1]`, double quotes, and escape sequences. To see a character vector in its "raw" form, you can use `cat(..., sep = '\n')`. The function `raw_string()` marks a character vector as "raw", and the corresponding printing function will call `cat(sep = '\n')` to print the character vector to the console.
58
59 ```{r}
60 library(xfun)
61 raw_string(head(LETTERS))
62 (x = c("a \"b\"", "hello\tworld!"))
63 raw_string(x) # this is more likely to be what you want to see
64 ```
65
66 ## Print the content of a text file
67
68 I have used `paste(readLines('foo'), collapse = '\n')` many times before I decided to write a simple wrapper function `xfun::file_string()`. This function also makes use of `raw_string()`, so you can see the content of a file in the console as a side-effect, e.g.,
69
70 ```{r comment=''}
71 f = system.file("LICENSE", package = "xfun")
72 xfun::file_string(f)
73 as.character(xfun::file_string(f)) # essentially a character string
74 ```
75
76 ## Get the data URI of a file
77
78 Files can be encoded into base64 strings via `base64_uri()`. This is a common technique to embed arbitrary files in HTML documents (which is [what `xfun::embed_file()` does](https://pkg.yihui.org/rmarkdown-cookbook/embed-file.html) and it is based on `base64_uri()`).
79
80 ```{r}
81 f = system.file("LICENSE", package = "xfun")
82 xfun::base64_uri(f)
83 ```
84
85 ## Match strings and do substitutions
86
87 After typing the code `x = grep(pattern, x, value = TRUE); gsub(pattern, '\\1', x)` many times, I combined them into a single function `xfun::grep_sub()`.
88
89 ```{r}
90 xfun::grep_sub('a([b]+)c', 'a\\U\\1c', c('abc', 'abbbc', 'addc', '123'), perl = TRUE)
91 ```
92
93 ## Search and replace strings in files
94
95 I can never remember how to properly use `grep` or `sed` to search and replace strings in multiple files. My favorite IDE, RStudio, has not provided this feature yet (you can only search and replace in the currently opened file). Therefore I did a quick and dirty implementation in R, including functions `gsub_files()`, `gsub_dir()`, and `gsub_ext()`, to search and replace strings in multiple files under a directory. Note that the files are assumed to be encoded in UTF-8. If you do not use UTF-8, we cannot be friends. Seriously.
96
97 All functions are based on `gsub_file()`, which performs searching and replacing in a single file, e.g.,
98
99 ```{r}
100 library(xfun)
101 f = tempfile()
102 writeLines(c("hello", "world"), f)
103 gsub_file(f, "world", "woRld", fixed = TRUE)
104 file_string(f)
105 ```
106
107 The function `gsub_dir()` is very flexible: you can limit the list of files by MIME types, or extensions. For example, if you want to do substitution in text files, you may use `gsub_dir(..., mimetype = '^text/')`.
108
109 The function `process_file()` is a more general way to process files. Basically it reads a file, process the content with a function that you pass to it, and writes back the text, e.g.,
110
111 ```{r}
112 process_file(f, function(x) {
113 rep(x, 3) # repeat the content 3 times
114 })
115 file_string(f)
116 ```
117
118 **WARNING**: Before using these functions, make sure that you have backed up your files, or version control your files. The files will be modified in-place. If you do not back up or use version control, there is no chance to regret.
119
120 ## Manipulate filename extensions
121
122 Functions `file_ext()` and `sans_ext()` are based on functions in **tools**. The function `with_ext()` adds or replaces extensions of filenames, and it is vectorized.
123
124 ```{r}
125 library(xfun)
126 p = c("abc.doc", "def123.tex", "path/to/foo.Rmd")
127 file_ext(p)
128 sans_ext(p)
129 with_ext(p, ".txt")
130 with_ext(p, c(".ppt", ".sty", ".Rnw"))
131 with_ext(p, "html")
132 ```
133
134 ## Find files (in a project) without the pain of thinking about absolute/relative paths
135
136 The function `proj_root()` was inspired by the **rprojroot** package, and tries to find the root directory of a project. Currently it only supports R package projects and RStudio projects by default. It is much less sophisticated than **rprojroot**.
137
138 The function `from_root()` was inspired by `here::here()`, but returns a relative path (relative to the project's root directory found by `proj_root()`) instead of an absolute path. For example, `xfun::from_root('data', 'cars.csv')` in a code chunk of `docs/foo.Rmd` will return `../data/cars.csv` when `docs/` and `data/` directories are under the root directory of a project.
139
140 ```
141 .
142 |-- data
143 | |-- cars.csv
144 |
145 |-- docs
146 |-- foo.Rmd
147 ```
148
149 If file paths are too much pain for you to think about, you can just pass an incomplete path to the function `magic_path()`, and it will try to find the actual path recursively under subdirectories of a root directory. For example, you may only provide a base filename, and `magic_path()` will look for this file under subdirectories and return the actual path if it is found. By default, it returns a relative path, which is relative to the current working directory. With the above example, `xfun::magic_path('cars.csv')` in a code chunk of `docs/foo.Rmd` will return `../data/cars.csv`, if `cars.csv` is a unique filename in the project. You can freely move it to any folders of this project, and `magic_path()` will still find it. If you are not using a project to manage files, `magic_path()` will look for the file under subdirectories of the current working directory.
150
151 ## Types of operating systems
152
153 The series of functions `is_linux()`, `is_macos()`, `is_unix()`, and `is_windows()` test the types of the OS, using the information from `.Platform` and `Sys.info()`, e.g.,
154
155 ```{r}
156 xfun::is_macos()
157 xfun::is_unix()
158 xfun::is_linux()
159 xfun::is_windows()
160 ```
161
162 ## Loading and attaching packages
163
164 Oftentimes I see users attach a series of packages in the beginning of their scripts by repeating `library()` multiple times. This could be easily vectorized, and the function `xfun::pkg_attach()` does this job. For example,
165
166 ```r
167 library(testit)
168 library(parallel)
169 library(tinytex)
170 library(mime)
171 ```
172
173 is equivalent to
174
175 ```r
176 xfun::pkg_attach(c('testit', 'parallel', 'tinytex', 'mime'))
177 ```
178
179 I also see scripts that contain code to install a package if it is not available, e.g.,
180
181 ```r
182 if (!requireNamespace('tinytex')) install.packages('tinytex')
183 library(tinytex)
184 ```
185
186 This could be done via
187
188 ```{r eval=FALSE}
189 xfun::pkg_attach2('tinytex')
190 ```
191
192 The function `pkg_attach2()` is a shorthand of `pkg_attach(..., install = TRUE)`, which means if a package is not available, install it. This function can also deal with multiple packages.
193
194 The function `loadable()` tests if a package is loadable.
195
196 ## Read/write files in UTF-8
197
198 Functions `read_utf8()` and `write_utf8()` can be used to read/write files in UTF-8. They are simple wrappers of `readLines()` and `writeLines()`.
199
200 ## Convert numbers to English words
201
202 The function `numbers_to_words()` (or `n2w()` for short) converts numbers to English words.
203
204 ```{r}
205 n2w(0, cap = TRUE)
206 n2w(seq(0, 121, 11), and = TRUE)
207 n2w(1e+06)
208 n2w(1e+11 + 12345678)
209 n2w(-987654321)
210 n2w(1e+15 - 1)
211 ```
212
213 ## Cache an R expression to disk or in memory
214
215 Since **xfun** v0.44, you are recommended to use the function [`cache_exec()`](https://pkg.yihui.org/xfun/manual.html#sec:man-cache_exec), which provides a simple yet flexible caching mechanism. See https://pkg.yihui.org/litedown/book/ for how it works. Previously, `cache_rds()` was mentioned here but it is no longer recommended (see [#100](https://github.com/yihui/xfun/issues/100)).
216
217 ## Check reverse dependencies of a package
218
219 Running `R CMD check` on the reverse dependencies of **knitr** and **rmarkdown** is my least favorite thing in developing R packages, because the numbers of their reverse dependencies are huge. The function `rev_check()` reflects some of my past experience in this process. I think I have automated it as much as possible, and made it as easy as possible to discover possible new problems introduced by the current version of the package (compared to the CRAN version). Finally I can just sit back and let it run.
220
221 ## Input a character vector into the RStudio source editor
222
223 The function `rstudio_type()` inputs characters in the RStudio source editor as if they were typed by a human. I came up with the idea when preparing my talk for rstudio::conf 2018 ([see this post](https://yihui.org/en/2018/03/blogdown-video-rstudio-conf/) for more details).
224
225 ## Print session information
226
227 Since I have never been fully satisfied by the output of `sessionInfo()`, I tweaked it to make it more useful in my use cases. For example, it is rarely useful to print out the names of base R packages, or information about the matrix products / BLAS / LAPACK. Oftentimes I want additional information in the session information, such as the Pandoc version when **rmarkdown** is used. The function `session_info()` tweaks the output of `sessionInfo()`, and makes it possible for other packages to append information in the output of `session_info()`.
228
229 You can choose to print out the versions of only the packages you specify, e.g.,
230
231 ```{r}
232 xfun::session_info(c('xfun', 'litedown', 'tinytex'), dependencies = FALSE)
233 ```
234