File: regex_subset_linter.Rd

package info (click to toggle)
r-cran-lintr 3.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,396 kB
  • sloc: sh: 13; xml: 10; makefile: 2
file content (61 lines) | stat: -rw-r--r-- 1,912 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
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/regex_subset_linter.R
\name{regex_subset_linter}
\alias{regex_subset_linter}
\title{Require usage of direct methods for subsetting strings via regex}
\usage{
regex_subset_linter()
}
\description{
Using \code{value = TRUE} in \code{\link[=grep]{grep()}} returns the subset of the input that matches
the pattern, e.g. \code{grep("[a-m]", letters, value = TRUE)} will return the
first 13 elements (\code{a} through \code{m}).
}
\details{
\code{letters[grep("[a-m]", letters)]} and \code{letters[grepl("[a-m]", letters)]}
both return the same thing, but more circuitously and more verbosely.

The \code{stringr} package also provides an even more readable alternative,
namely \code{str_subset()}, which should be preferred to versions using
\code{str_detect()} and \code{str_which()}.
}
\section{Exceptions}{

Note that \code{x[grep(pattern, x)]} and \code{grep(pattern, x, value = TRUE)}
are not \emph{completely} interchangeable when \code{x} is not character
(most commonly, when \code{x} is a factor), because the output of the
latter will be a character vector while the former remains a factor.
It still may be preferable to refactor such code, as it may be faster
to match the pattern on \code{levels(x)} and use that to subset instead.
}

\examples{
# will produce lints
lint(
  text = "x[grep(pattern, x)]",
  linters = regex_subset_linter()
)

lint(
  text = "x[stringr::str_which(x, pattern)]",
  linters = regex_subset_linter()
)

# okay
lint(
  text = "grep(pattern, x, value = TRUE)",
  linters = regex_subset_linter()
)

lint(
  text = "stringr::str_subset(x, pattern)",
  linters = regex_subset_linter()
)

}
\seealso{
\link{linters} for a complete list of linters available in lintr.
}
\section{Tags}{
\link[=best_practices_linters]{best_practices}, \link[=efficiency_linters]{efficiency}, \link[=regex_linters]{regex}
}