-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathfgsub.R
More file actions
192 lines (170 loc) · 5.99 KB
/
Copy pathfgsub.R
File metadata and controls
192 lines (170 loc) · 5.99 KB
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
#' Replace a Regex with an Functional Operation on the Regex Match
#'
#' This is a stripped down version of \code{gsubfn} from the \pkg{gsubfn}
#' package. It finds a regex match, and then uses a function to operate on
#' these matches and uses them to replace the original matches. Note that
#' the \pkg{stringi} packages is used for matching and extracting the regex
#' matches. For more powerful or flexible needs please see the \pkg{gsubfn}
#' package.
#'
#' @param x A character vector.
#' @param pattern Character string to be matched in the given character vector.
#' @param fun A function to operate on the extracted matches.
#' @param \ldots ignored.
#' @return Returns a vector with the pattern replaced.
#' @export
#' @importFrom data.table :=
#' @seealso \code{\link[gsubfn]{gsubfn}}
#' @examples
#' ## In this example the regex looks for words that contain a lower case letter
#' ## followed by the same letter at least 2 more times. It then extracts these
#' ## words, splits them appart into letters, reverses the string, pastes them
#' ## back together, wraps them with double angle braces, and then puts them back
#' ## at the original locations.
#' fgsub(
#' x = c(NA, 'df dft sdf', 'sd fdggg sd dfhhh d', 'ddd'),
#' pattern = "\\b\\w*([a-z])(\\1{2,})\\w*\\b",
#' fun = function(x) {
#' paste0('<<', paste(rev(strsplit(x, '')[[1]]), collapse =''), '>>')
#' }
#' )
#'
#' ## In this example we extract numbers, strip out non-digits, coerce them to
#' ## numeric, cut them in half, round up to the closest integer, add the commas
#' ## back, and replace back into the original locations.
#' fgsub(
#' x = c(NA, 'I want 32 grapes', 'he wants 4 ice creams',
#' 'they want 1,234,567 dollars'
#' ),
#' pattern = "[\\d,]+",
#' fun = function(x) {
#' prettyNum(
#' ceiling(as.numeric(gsub('[^0-9]', '', x))/2),
#' big.mark = ','
#' )
#' }
#' )
#'
#' ## In this example we extract leading zeros, convert to an equal number of
#' ## spaces.
#' fgsub(
#' x = c(NA, "00:04", "00:08", "00:01", "06:14", "00:02", "00:04"),
#' pattern = '^0+',
#' fun = function(x) {gsub('0', ' ', x)}
#' )
fgsub <- function(x, pattern, fun, ...){
hit_id <- pattern_id <- pat <- placeholder <- NULL
locs <- stringi::stri_detect_regex(x, pattern)
locs[is.na(locs)] <- FALSE
txt <- x[locs]
hits <- stringi::stri_extract_all_regex(txt, pattern)
## Make unique replacement substrings
h <- lengths(hits)
y <- sum(h)
if (y == 0) return(x)
counter <- ceiling(y/26)
## Make a replacement key
pats <- unique(unlist(hits))
reps <- paste0("textcleanholder", seq_along(pats), "textcleanholder")
freps <- unlist(lapply(pats, fun))
pat_key <- data.table::data.table(pat = pats, replacement = freps, placeholder = reps)
## Matches and their corresponding placeholder
all_hits <- unlist(hits)
## Maintain order
placeholders <- pat_key$placeholder[match(all_hits, pat_key$pat)]
hit_key <- data.table::data.table(
hit_id = rep(seq_len(length(h)), h),
pat = placeholders,
pattern_id = unlist(lapply(h, seq_len))
)
data.table::setkey(pat_key, placeholder)
data.table::setkey(hit_key, pat)
hit_key <- hit_key[pat_key][,
hit_id := as.integer(hit_id)][,
pattern_id := as.integer(pattern_id)]
data.table::setorderv(hit_key, cols = c('hit_id', 'pattern_id'))
## Loop through and replace the first pattern in each element with a unique
# replacement substring
for (i in seq_len(nrow(hit_key))) {
hkr <- hit_key[i,]
txt[hkr[, 'hit_id'][[1]]] <- stringi::stri_replace_first_regex(
txt[hkr[, 'hit_id'][[1]]],
pattern,
hkr[, 'pat'][[1]]
)
}
## Because the unique repalcment substrings are so unlikely to have a
## collision, we can use fixed = TRUE and be very quick here
txt <- mgsub(txt, hit_key[['pat']], hit_key[['replacement']], fixed = TRUE, ...)
x[locs] <- txt
x
}
## defunct version 2018-06-06
# fgsub <- function(x, pattern, fun, ...){
#
# hit_id <- pattern_id <- pat <- NULL
#
# locs <- stringi::stri_detect_regex(x, pattern)
# locs[is.na(locs)] <- FALSE
# txt <- x[locs]
#
# hits <- stringi::stri_extract_all_regex(txt, pattern)
#
#
# pats <- unique(unlist(hits))
# reps <- paste0("textcleanholder", seq_along(pats), "textcleanholder")
# freps <- unlist(lapply(pats, fun))
#
# pat_key <- data.table::data.table(pat = pats, replacement = freps)
#
# hit_key <- textshape::tidy_list(
# set_names(
# lapply(hits, function(x) set_names(x, seq_along(x))),
# seq_along(hits)
# ),
# 'hit_id', 'pat', 'pattern_id'
# )
#
#
# data.table::setkey(pat_key, pat)
# data.table::setkey(hit_key, pat)
#
# hit_key <- hit_key[pat_key][,
# hit_id := as.integer(hit_id)][,
# pattern_id := as.integer(pattern_id)]
#
# data.table::setorderv(hit_key, cols = c('hit_id', 'pattern_id'))
#
# for (i in seq_len(nrow(hit_key))) {
# hkr <- hit_key[i,]
# hkr[, 'pattern_id'][[1]]
# txt[hkr[, 'hit_id'][[1]]] <- sub(
# hkr[, 'pat'][[1]],
# hkr[, 'replacement'][[1]],
# txt[hkr[, 'hit_id'][[1]]],
# perl = TRUE
# )
# }
#
# x[locs] <- txt
# x
#
# }
## old version removed 2018-06-01
# fgsub <- function(x, pattern, fun, ...){
#
# locs <- stringi::stri_detect_regex(x, pattern)
# locs[is.na(locs)] <- FALSE
# txt <- x[locs]
#
# hits <- stringi::stri_extract_all_regex(txt, pattern)
# pats <- unique(unlist(hits))
# reps <- paste0('textcleanholder', seq_along(pats), 'textcleanholder')
# freps <- unlist(lapply(pats, fun))
#
# txt <- mgsub(txt, pats, reps)
#
# x[locs] <- mgsub(txt, reps, freps)
# x
#
# }