R: How to replace space (' ') in string with a *single* backslash and space ('\ ')
<p>I've searched many times, and haven't found the answer here or elsewhere. I want to replace each space <code>' '</code> in variables containing file names with a <code>'\ '</code>. (A use case could be for shell commands, with the spaces escaped, so each file name doesn't appear as a list of arguments.) I have looked through the StackOverflow question <a href="https://stackoverflow.com/questions/27491986/r-gsub-replacing-backslashes">"how to replace single backslash in R"</a>, and find that many combinations do work as advertised:</p>

<pre><code>&gt; gsub(" ", "\\\\", "a b")
[1] "a\\b"

&gt; gsub(" ", "\\ ", "a b", fixed = TRUE)
[1] "a\\ b"
</code></pre>

<p>but try these with a single-slash version, and R ignores it:</p>

<pre><code>&gt; gsub(" ", "\\ ", "a b")
[1] "a b"

&gt; gsub(" ", "\ ", "a b", fixed = TRUE)
[1] "a b"
</code></pre>

<p>For the case going in the opposite direction — removing slashes from a string, it works for two:</p>

<pre><code>&gt; gsub("\\\\", " ", "a\\b")
[1] "a b"

&gt; gsub("\\", " ", "a\\b", fixed = TRUE)
[1] "a b"
</code></pre>

<p>However, for single slashes some inner perversity in R prevents me from even attempting to remove them:</p>

<pre><code>&gt; gsub("\\", " ", "a\\b")
Error in gsub("\\", " ", "a\\b") : 
  invalid regular expression '\', reason 'Trailing backslash'

&gt; gsub("\", " ", "a\b", fixed = TRUE)
Error: unexpected string constant in "gsub("\", " ", ""
</code></pre>

<p>The 'invalid regular expression' is telling us something, but I don't see what. (Note too that the <code>perl = True</code> option does not help.)</p>

<p>Even with three back slashes R fails to notice even one:</p>

<pre><code>&gt; gsub(" ", "\\\ ", "a b")
[1] "a b"
</code></pre>

<p>The patter extends too! Even multiples of two work:</p>

<pre><code>&gt; gsub(" ", "\\\\\\\\", "a b")
[1] "a\\\\b"
</code></pre>

<p>but not odd multiples (should get <code>'\\\ '</code>:</p>

<pre><code>&gt; gsub(" ", "\\\\\\ ", "a b")
[1] "a\\ b"

&gt; gsub(" ", "\\\ ", "a b", fixed = TRUE)
[1] "a\\ b"
</code></pre>

<p>(I would expect 3 slashes, not two.)</p>

<p>My two questions are:</p>

<ul>
<li>How can my goal of replacing a <code>' '</code> with a <code>'\ '</code> be accomplished?</li>
<li>Why did the odd number-slash variants of the replacements fail, while the even number-slash replacements worked?</li>
</ul>

<p>For shell commands a simple work-around is to quote the file names, but part of my interest is just wanting to understand what is going on with R's regex engine.</p>