OneBite.Dev - Coding blog in a bite size

remove a substring from a string in R

Code snippet on how to remove a substring from a string in R

  myString <- "this is a test string"
  subString <- "test"
  newString <- gsub(subString, "", myString)

This code is used to remove a substring from a string in R. The first line creates a variable called myString and sets it to the string “this is a test string”. The second line creates a variable called subString and sets it to the string “test”. The third line creates a variable called newString and sets it to the result of using the gsub() function. The gsub function takes two arguments, the first is the subString variable, the second is an empty string, which is used to remove the targeted substring. The gsub function then returns a new version of the myString variable with the targeted substring removed. The result is stored in the newString variable. The newString variable will now contain the string “this is a string”.

r