Find and replace entire value in R

前端 未结 4 933
青春惊慌失措
青春惊慌失措 2021-01-24 04:29

I\'m looking for a way to use the find and replace function in R to replace the entire value of a string, rather than just the matching part of the string. I have a dataset with

4条回答
  •  粉色の甜心
    2021-01-24 05:03

    You can use gsub as follows:

     gsub(".*experiences.*", "exp", string, perl=TRUE) 
     # As @rawr notes, set perl=TRUE for improved efficiency
    

    This regex matches strings that have any characters 0 or more times (i.e. .*) followed by "experiences", followed by any characters 0 or more times.

    In this case, you are still replacing the entire match with "exp" but by using regex, you expand the definition of the match (from "experience" to ".*experience.*") to achieve the desired substitution.

提交回复
热议问题