The |
symbol is a special character for regular expressions, and must be escaped. This symbol means to or the two possibilities. Here, you're saying to replace a space or a space with a |
. That is, replace each space with a |
, which is what it did.
I prefer to use a character class to an escape, which also works:
gsub(pattern=" [|] ",replacement="|",x=adgroupname)
## [1] "life sciences|medical device"
Same result, but you have fewer backslashes to count.
It's not the case here, but when you must pass the regular expression through a shell to another process, counting the backslashes gets very tedious.