The “gsub” Function in R

  • Package: Base R (No specific package, it’s a built-in function)

  • Purpose: To replace all occurrences of a pattern in a character vector with a specified replacement string.

  • General Class: String Manipulation

  • Required Argument(s):

    • pattern: A character string or a regular expression specifying the pattern to be replaced.

    • replacement: A character string specifying the replacement for the pattern.

    • x: A character vector in which replacements are to be made.

  • Notable Optional Arguments:

    • ignore.case: Logical. If TRUE, the pattern matching is case-insensitive. The default is FALSE.

    • perl: Logical. If TRUE, use Perl-style regular expressions. The default is FALSE.

  • Example:

  • # Example usage
    sentence <- "The quick brown fox jumps over the lazy dog."

    # Replace "fox" with "cat" in the sentence
    modified_sentence <- gsub(pattern = "fox", replacement = "cat", x = sentence)

    print(modified_sentence)

  • In this example, gsub is a built-in function in base R, and it is used to replace all occurrences of the specified pattern (“fox”) in a character vector (sentence) with the specified replacement string (“cat”). The pattern, replacement, and x arguments are required, and additional optional arguments, such as ignore.case and perl, can be used to modify the behavior of the pattern matching. The result is a character vector with the specified replacements.

Previous
Previous

The “sub” Function in R

Next
Next

The “strsplit” Function in R