I keep having to manually convert my back slashes to front slashes. Is there a quick way of doing this through a function in R?

Example, copied from Windows Explorer:

G:\Compensation Audits_Reports\Step Audit\Steps off Step.accdb

R snippet example:

testdb<-file.path("G:/Compensation Audits_Reports/Step Audit/Steps off Step.accdb")
  • maybe I shoudl have stripped of the examples to make it more generic looking? – daniellopez46 Jun 14 '12 at 21:19
  • No, the examples are good and important. That didn't mean to coma across that negative but you have to understand that often, users who are question banned or suspended post their questions on other sites, and the community tries to migrate them back where they belong, only to find out that it's blocked by the system, which is just confusing. – slhck Jun 14 '12 at 21:31
  • But how am I off topic when what I was asking for was a function not someone to edit my code? Its the same as other posts that exist out there and they were not closed. Examples: 1. Example1 2.Example2. – daniellopez46 Jun 14 '12 at 21:48
  • 1
    I think in this case the question should be reopened, so I'm doing that. – nhinkle Jun 15 '12 at 0:23
  • See stackoverflow.com/a/8425591/903061 for a neat solution. – Gregor Feb 27 '13 at 0:05

Using sub function, you can do

sub("\\\\","/","G:\\Compensation\\Step Audit\\Steps off Step.accdb")
  • @Silva thanks for the earlier edit suggestion. I copied and pasted what you wrote and got: Error: '\C' is an unrecognized escape in character string starting "G:\C" – daniellopez46 Jun 14 '12 at 21:19

It seems this is actually not possible because the windows paths are understood by R in such a way that the "\" escape the next character. Something like: "foo\bar" is perceived as some characters (foo) followed by the special \b character followed by some other, normal characters (ar).

To transform single "\" to "/" you first have to escape them by a backslash which would look like this: "foo\\bar" , which in the most cases is ridiculous because then you can as well transform the backslashes to slashes manually.

The only thing that may help was this post on StackOverflow giving the code for a function capturing the input into the console directly and then transforming it. So with this you might get a Rfriendly path via copy paste.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.