Home > other >  Contain and substitute
Contain and substitute

Time:11-08

It is possible substitute a word in a column that contains specific characters? I would like to change the character "osa" in the set. What can I do?

iris
iris$Species <- gsub(contains("osa"), "set", iris$Species, fixed = TRUE)

CodePudding user response:

Edit: To return only set. You can use the .* wildcard before and after your pattern (though in your particular example you only need it before)

table(gsub(".*osa.*", "set", iris$Species))
#
#       set versicolor  virginica 
#        50         50         50 

Original answer:

gsub() already looks across the whole string for the pattern.

gsub("osa", "set", iris$Species, fixed = TRUE)

 table(iris$Species)
#
#    setosa versicolor  virginica 
#        50         50         50 
 table(gsub("osa", "set", iris$Species, fixed = TRUE))
#
#    setset versicolor  virginica 
#        50         50         50 

CodePudding user response:

Use grepl to find which rows to update, then assign:

iris$Species <- as.character(iris$Species)

table(iris$Species)
# setosa versicolor  virginica 
#     50         50         50 

iris$Species[ grepl("osa", iris$Species, fixed = TRUE) ] <- "set"

table(iris$Species)
# set versicolor  virginica 
#  50         50         50
  • Related