aped
aped

Reputation: 27

Replacing a string that contains a certain word with that word

I have a column in my df with many different strings, for instance a string would say crossed at point a, or came in through point a. I want to replace that entire string with just a, how could I go about doing this?

Upvotes: 1

Views: 581

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76673

Following a comment to the question by user Allan Cameron, here is a full solution with the suggestion I made.

df1 <- data.frame(col = c("crossed at point a", 
                          "doesn't match though it has as", 
                          "came in through point a", 
                          "no"))

df1$col[grepl("\\ba\\b", df1$col)] <- "a"
df1
#                              col
#1                               a
#2  doesn't match though it has as
#3                               a
#4                              no

Edit

Following another comment by Allan Cameron I have decided to write a small function to make it easier to replace a string that contains a word by that word.

replaceWord <- function(x, word){
  pattern <- paste0("\\b", word, "\\b")
  i <- grep(pattern, x)
  x[i] <- word
  x
}

replaceWord(df1$col, "a")

Upvotes: 2

Related Questions