spies006
spies006

Reputation: 2927

Replace text in column if matches specific pattern in R dataframe

If I have the following column in a data frame:

df$column <- c("store", "the store", "factory", "factory A")

I want to search for an occurrence of 'store' in df$column if we find a row that contains 'store' then replace it with 'store'. So if we come across 'the store' it should be replaced with 'store' because 'store' is contained in this instance.

So a resulting output would be:

"store", "store", "factory", "factory A"

Upvotes: 0

Views: 345

Answers (1)

Gaurav Bansal
Gaurav Bansal

Reputation: 5670

Use grep: df$column[grep("store", df$column)] <- "store"

Upvotes: 3

Related Questions