-
Notifications
You must be signed in to change notification settings - Fork 2
/
stringfunc.R
48 lines (34 loc) · 1.24 KB
/
stringfunc.R
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
#!/usr/bin/env Rscript
local({
tmp_require_package_namespace <- function(...) {
packages <- as.character(match.call(expand.dots = FALSE)[[2]])
for (p in packages) if (!requireNamespace(p)) install.packages(p)
}
tmp_require_package_namespace(
gsubfn
)
})
# =============================================================================
# Top-level namespace: %format%
# =============================================================================
# https://stackoverflow.com/questions/17475803/sprintf-format-strings-reference-by-name
`%format%` <- function(fmt, list) {
pat <- "%\\(([^)]*)\\)"
fmt2 <- gsub(pat, "%", fmt)
list2 <- list[strapplyc(fmt, pat)[[1]]]
do.call("sprintf", c(fmt2, list2))
}
# =============================================================================
# Namespace-like method: http://stackoverflow.com/questions/1266279/#1319786
# =============================================================================
stringfunc <- new.env()
stringfunc$formatString <- function(fmt, list) {
return(with(list, gsubfn::fn$identity(fmt)))
}
stringfunc$TESTS <- '
stringfunc$formatString("some $text $to $replace", list(
text = "day",
to = "in",
replace = "June"
))
'