OneBite.Dev - Coding blog in a bite size

trim a string in R

Code snippet on how to trim a string in R

trimmed_string <- gsub("^\\s+|\\s+$", "", string)

This code trims a string from any unwanted whitespace before or after it. It uses the gsub() function, which stands for Global Substitution, to find and replace all instances of the pattern provided in the string. In this case, the pattern is two regular expressions: ”^\s+” and “\s+$”, which stands for whitespace at the beginning of the string, and whitespace at the end of the string, respectively. Finally, the matched pattern is replaced with an empty string, effectively removing the whitespace. The result is stored in a variable named trimmed_string.

r