[R] How to convert backslash to slash?

Shengqiao Li shli at stat.wvu.edu
Wed Sep 24 14:53:22 CEST 2008


On Wed, 24 Sep 2008, Duncan Murdoch wrote:

> Shengqiao Li wrote:
>> On Tue, 23 Sep 2008, Duncan Murdoch wrote:
>> 
>> 
>>> On 23/09/2008 4:00 PM, Shengqiao Li wrote:
>>> 
>>>> How to use sub, gsub, etc. to replace "\" in a string to "/"?
>>>> 
>>>> For example,convert "C:\foo\bar" to "C:/foo/bar".
>>>> 
>>> If those are R strings, there are no backslashes in the first one.  It has 
>>> a formfeed and a backspace in it.
>>> 
>> 
>> I did notice that this string  was special. It's a legimate R string. If 
>> "f" and "b" are replaced by "d", it will not. 
>
> I didn't say it was not legitimate, I said that it contains no backslashes. 
> If you replace f or b with d, you do not have a legitimate string.
>> My purpose is to convert a Windows file path (eg. copied from Explorer 
>> location bar) to a R file path through some R function inside R terminal. 
>> The "File->Change dir..." takes a file path like "C:\Acer", but setwd 
>> function will fail. 
>
> That's not true.  If you enter a backslash in the string, setwd() works fine.
>
> Your problem is that you are confusing R source code with the strings that it 
> represents.  The R source code for the file path C:\Acer is "C:\\Acer".  The
> R source code "C:\foo\bar" contains no backslashes, it contains the 
> characters C, :, formfeed, o, o,  backspace, a, r.
>
> If you have the string C:\Acer in the Windows clipboard, then you can read it 
> from there using readClipboard().  (There are many other ways to read the 
> clipboard as well;
> using 'clipboard' as a filename generally works.) You can then pass it to 
> setwd(), and it will be fine.

Thank you for your reply. readClipboard is a partial solution to this 
case. More generally, if I want to wrtie a R program in which users are 
asked to input a file path. I want this program to be robust and tolerant, 
that is users can type in C:\Acer or C:/Acer.  What's the way to do this?

Shengqiao Li

>
> Duncan Murdoch
>> I guess there must be some ways in R to replace a backslash by slash, eg. 
>> C:\Acer -> C:/Acer. The first problem may be how to pass and save this kind 
>> of strings. encodeString does not work for this, it will just ignore "\".
>>   Shengqiao Li
>> 
>> 
>>> Duncan Murdoch
>>> 
>>> 
>> 
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide 
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>> 
>
>



More information about the R-help mailing list