Message-ID: <m2irryexde.fsf@fhcrc.org>
Date: 2006-02-01T18:40:13Z
From: Seth Falcon
Subject: inserting one backslash
In-Reply-To: <43E0F4BC.60404@rhkoning.com> (RH Koning's message of "Wed, 01 Feb 2006 18:49:48 +0100")
On 1 Feb 2006, mailing-lists at rhkoning.com wrote:
> Hello, I am not very familiar with regular expressions and
> escaping. I need to replace the %-signs in a character vector with
> elements as "income 0%-33%# to be replaced by "income 0\%-33\%" (for
> later use in LaTeX). Using
>
> gsub("%","\\%","income 0%-33%")
>
> does not give the desired result. However, gsub("%","\\\\%","income
> 0%-33%") gives "income 0\\%-33\\%", one backslash too much. What is
> the appropriate expression to get the desired output (one backslash
> before each %-sign)?
I think you are on the right track with the second pattern "\\\\%".
There is a difference between what print(s) will display and what
cat(s) will display.
> gsub("%", "\\\\%", "income 0%-33%")
[1] "income 0\\%-33\\%"
> cat(gsub("%", "\\\\%", "income 0%-33%"), "\n")
income 0\%-33\%
The string "\\" in R contains one character (see nchar()), not two.
It can be confusing.
HTH,
+ seth