Working with Strings
strings.Rd
Tools for working with character/text strings without importing the stringr package.
Arguments
- x
A character vector.
- width
integer(1)
. The minimum width of padding for each element.- side
character(1)
. Pad to the left or right.- whitespace
A string specifying a regular expression to match (one character of) "white space".
- text
A character vector where matches are sought.
- pattern
character(1)
. A string containing a group capture regex.
Functions
pad()
: Similar tostringr::str_pad()
but does uses only a blank space as the padding character.squish()
: The inverse ofpad()
, removes whitespace on both sides and replicated internal whitespace. Similar tostringr::str_squish()
.trim()
: A wrapper aroundtrimws()
but with unified argument names.capture()
: Uses "group capture" regular expression from thepattern
argument to extract matches from character string(s). Analogous tostringr::str_extract()
.
base vs stringr
Below is a convenient table of the stringr to base R equivalents:
stringr | base R |
stringr::str_c() | paste() |
stringr::str_count() | gregexpr() + attr(x, "match.length") ] |
stringr::str_dup() | strrep() |
stringr::str_detect() | grepl() |
stringr::str_flatten() | paste(..., collapse = "") |
stringr::str_glue() | sprintf() |
stringr::str_length() | nchar() |
stringr::str_locate_all() | regexpr() |
stringr::str_match() | match() |
stringr::str_order() | order() |
stringr::str_remove() | sub(..., replacement = "") |
stringr::str_remove_all() | gsub(..., replacement = "") |
stringr::str_replace() | sub() |
stringr::str_replace_all() | gsub() |
stringr::str_sort() | sort() |
stringr::str_split() | strsplit() |
stringr::str_sub() | substr() , substring() , strtrim() |
stringr::str_subset() | grep(..., value = TRUE) |
stringr::str_to_lower() | tolower() |
stringr::str_to_upper() | toupper() |
stringr::str_trim() | trimws() |
stringr::str_which() | grep() |
stringr::str_wrap() | strwrap() |
And those found only in helpr:
stringr | helpr |
stringr::str_extract() | capture() , gsub(..., replacement = "\\1") |
stringr::str_squish() | squish() |
stringr::str_pad() | pad() or sprintf() |
stringr::str_trim() | trim() |
Examples
pad("tidyverse", 20)
#> [1] "tidyverse "
pad("tidyverse", 20, "left")
#> [1] " tidyverse"
pad("tidyverse", 20, "both")
#> [1] " tidyverse "
squish(" abcd efgh ")
#> [1] "abcd efgh"
squish(" abcd efgh .")
#> [1] "abcd efgh ."
trim(" abcd efgh ")
#> [1] "abcd efgh"
trim(" abcd efgh .")
#> [1] "abcd efgh ."
# extract the group 'oo'
capture(c("foo", "bar", "boo", "oops"), "(oo)")
#> 1
#> 1 oo
#> 2 <NA>
#> 3 oo
#> 4 oo
# capture multiple groups
capture(c("foo", "bar", "boo", "oops-e-doo"), "(.*)(oo)")
#> 1 2
#> 1 f oo
#> 2 <NA> <NA>
#> 3 b oo
#> 4 oops-e-d oo