stringr

repository·main·Indexed 20 days ago

https://github.com/tidyverse/stringr

A tidyverse package providing a cohesive and consistent set of functions for string manipulation in R. Built on top of the high-performance stringi package and the ICU C library, stringr uses a consistent str_ prefix for its functions and takes a vector of strings as the first argument to ensure compatibility with the R pipe operator.

Tokens
2.2K
Snippets
9
Records
12
Agent score
21%

What's inside stringr

  1. Overview of stringr

    main
    stringr provides a cohesive set of functions for string manipulation in R. It is built on top of the stringi package, which uses the ICU C library for high-performance and correct string operations. While stringr focuses on the most commonly used functions, stringi provides a more comprehensive, exhaustive set of tools. Because they share similar conventions, skills learned in stringr are easily transferable to stringi.
  2. Basic string manipulation with stringr

    main

    All stringr functions follow a consistent pattern: they start with the str_ prefix and take a vector of strings as the first argument. This makes them highly compatible with the R pipe operator (%>%).

    x <- c("why", "video", "cross", "extra", "deal", "authority")
    str_length(x) 
    #> [1] 3 5 5 5 4 9
    
    str_c(x, collapse = ", ")
    #> [1] "why, video, cross, extra, deal, authority"
    
    str_sub(x, 1, 2)
    #> [1] "wh" "vi" "cr" "ex" "de" "au"
  3. Pattern matching engines in stringr

    main

    While regular expressions are the default, stringr supports three other pattern matching engines to control how patterns are interpreted:

    • fixed(): Matches exact bytes.
    • coll(): Matches human letters (collation).
    • boundary(): Matches boundaries.
  4. Advantages of stringr over base R

    main

    Compared to base R string operations, stringr offers several improvements:

    • Consistency: Functions use consistent names and argument orders. The first argument is always the vector of strings, which facilitates piping.
    • Simplicity: It eliminates many complex options that are rarely used, focusing on the 95% use case.
    • Predictability: Outputs are designed to be easily used as inputs (e.g., missing inputs result in missing outputs, and zero-length inputs result in zero-length outputs).
    # Example of piping with stringr
    letters %>%
      .[1:10] %>%
      str_pad(3, "right") %>%
      str_c(letters[2:11])
    #>  [1] "a  b" "b  c" "c  d" "d  e" "e  f" "f  g" "g  h" "h  i" "i  j" "j  k"
  5. Install the RegExplain RStudio Addin

    main

    The RegExplain RStudio addin provides an interactive interface for building regular expressions and testing stringr functions. You can install it using devtools from GitHub.

    # install.packages("devtools")
    devtools::install_github("gadenbuie/regexplain")
  6. Install stringr

    main

    You can install stringr either as part of the full tidyverse suite or as a standalone package.

    # The easiest way to get stringr is to install the whole tidyverse:
    install.packages("tidyverse")
    
    # Alternatively, install just stringr:
    install.packages("stringr")
  7. Resolve `stringr::str_replace_all` length validation errors in latex2exp

    main

    In the package latex2exp (0.9.6), tests are failing during str_replace_all calls. The backtrace indicates issues within stringr:::check_lengths during pattern replacement operations involving LaTeX escape sequences.

    Error context:

    stringr::str_replace_all(., "([^\\\\\\]?)\\\\s", "\\1\\@SPACE2{}")
    # ... followed by internal check_lengths calls

    Review the patterns and replacement strings used in latex2exp to ensure they comply with stringr length and type requirements.

  8. Fix `stringr::str_replace_all` replacement function return type in NMsim

    main

    In the package NMsim (v0.2.5), a test failure occurs because the replacement function passed to stringr::str_replace_all returns a double vector instead of a character vector. To fix this, ensure the function used as the replacement argument returns character strings.

    Error context:

    Error in `stringr::str_replace_all(mod$THETA, "\\d+\\.\\d+", function(x) round(as.numeric(x), 
        digits = 3))`: `replacement` function must return a character vector, not a double
    vector.
    # Incorrect usage causing error:
    stringr::str_replace_all(mod$THETA, "\\d+\\.\\d+", function(x) round(as.numeric(x), digits = 3))
    
    # Correct usage (ensure character return):
    stringr::str_replace_all(mod$THETA, "\\d+\\.\\d+", function(x) as.character(round(as.numeric(x), digits = 3)))
  9. Troubleshoot `str_replace_all()` replacement function errors

    main

    When using stringr::str_replace_all() with a function as the replacement argument, the function must be able to handle a character vector of any length and return a vector of the same length as the input.

    Common errors include:

    • Length Mismatch: The replacement function returns a vector of length 1 when the input vector has a different length (e.g., length 47).
    • Non-vectorized logic: The replacement function uses conditional logic (like if (condition)) that fails when the input is a vector of length > 1.
    • NA patterns: The pattern argument passed to str_replace() cannot contain NA values.
    # Example of a failing pattern: replacement function returning wrong length
    salt_replace(x, replacement_shaker$capitalization, p = 0.5, rep_p = 0.2)
    # Error: `replacement` function must return a vector the same length as the input (47), not length 1.
    
    # Example of a failing pattern: non-vectorized replacement function
    stringr::str_replace_all(eqn, pattern = pattern, replacement = reformat_scientific)
    # Error: Failed to apply `replacement` function. It must accept a character vector of any length.
  10. Fix `stringr::str_replace` pattern NA error in nrlR

    main

    In the package nrlR (v0.1.1), an error occurs during fetch_lineups because the pattern argument passed to stringr::str_replace contains NA values.

    Error context:

    Error in `stringr::str_replace()`:
    ! `pattern` can not contain NAs.

    Ensure that the pattern being passed to str_replace is a valid character string and does not contain NA.

    # The error occurs here:
    stringr::str_replace(rvest::html_text2(home_node), home_role_full, "")
    # Ensure 'home_role_full' is not NA
  11. Ensure `str_replace()` patterns do not contain NAs

    main

    When calling stringr::str_replace() or stringr::str_remove(), ensure that the pattern argument does not contain NA values. Passing an NA as a pattern will cause a runtime error during test execution or data processing.

    # Error context from zipangu:
    # Caused by error in `str_replace()`:
    # ! `pattern` can not contain NAs.
  12. Pattern matching verbs in stringr

    main

    Most string functions in stringr work with regular expressions. There are seven primary 'verbs' used to interact with patterns:

    • str_detect(x, pattern): Returns a logical vector indicating if a match exists.
    • str_count(x, pattern): Counts the number of pattern matches in each string.
    • str_subset(x, pattern): Extracts the elements of the vector that match the pattern.
    • str_locate(x, pattern): Returns the start and end positions of the matches.
    • str_extract(x, pattern): Extracts the actual text of the match.
    • str_match(x, pattern): Extracts parts of the match defined by capture groups (parentheses).
    • str_replace(x, pattern, replacement): Replaces matches with new text.
    • str_split(x, pattern): Splits a string into multiple pieces based on the pattern.
    x <- c("why", "video", "cross", "extra", "deal", "authority")
    
    # Example: Extracting characters on either side of a vowel using capture groups
    str_match(x, "(.)[aeiou](.)")
    #>      [,1]  [,2] [,3] 
    #> [1,] NA    NA   NA  
    #> [2,] "vid" "v"  "d" 
    #> [3,] "ros" "r"  "s" 
    #> [4,] NA    NA   NA  
    #> [5,] "dea" "d"  "a" 
    #> [6,] "aut" "a"  "t"