Learn R Programming

DataCombine (version 0.2.21)

FindReplace: Replace multiple patterns found in a character string column of a data frame

Description

FindReplace allows you to find and replace multiple character string patterns in a data frame's column.

Usage

FindReplace(data, Var, replaceData, from = "from", to = "to", exact = TRUE, vector = FALSE)

Arguments

data
data frame with the column you would like to replace string patterns.
Var
character string naming the column you would like to replace string patterns. The column must be of class character or factor.
replaceData
a data frame with at least two columns. One contains the patterns to replace and the other contains their replacement. Note: the pattern and its replacement must be in the same row.
from
character string naming the column with the patterns you would like to replace.
to
character string naming the column with the the pattern replacements.
exact
logical. Indicates whether to only replace exact pattern matches (TRUE) or not (FALSE).
vector
logical. If TRUE then the replacement is returned as a single vector. If FALSE then the whole data frame is returned.

Examples

Run this code
# Create original data
ABData <- data.frame(a = c("London, UK", "Oxford, UK", "Berlin, DE",
                     "Hamburg, DE", "Oslo, NO"),
                     b = c(8, 0.1, 3, 2, 1))

# Create replacements data frame
Replaces <- data.frame(from = c("UK", "DE"), to = c("England", "Germany"))

# Replace patterns and return full data frame
ABNewDF <- FindReplace(data = ABData, Var = "a", replaceData = Replaces,
                     from = "from", to = "to", exact = FALSE)

# Replace patterns and return the Var as a vector
ABNewVector <- FindReplace(data = ABData, Var = "a", replaceData = Replaces,
                     from = "from", to = "to", vector = TRUE)

Run the code above in your browser using DataLab