How can I remove multiple spaces and trailing spaces using only 1 gsub? I already made this function trim <- function(x) gsub(\' {2,}\',\' \',gsub(\'^ *| *$\',\'\',
trim <- function(x) gsub(\' {2,}\',\' \',gsub(\'^ *| *$\',\'\',
Use a positive lookbehind to see if the current space is preceded by a space:
^ *|(?<= ) | *$
See it here in action: http://regex101.com/r/bJ1mU0