Convert backslash to forward slash in R non-interactively - r

I'm trying to take an input path and convert the slashes from backwards to forwards as part of an R package. There are some suggestions to do this here and elsewhere, but all of these solutions require some amount of interaction by the user: either copying a path, or selecting a path from a prompt. I would be happy if I could find a solution that works on strings, but when I try to use strings with slashes in R, I run into problems.
# example path
path <- "C:\aaa\bbb\fff\"\n" # I have to add this \n linebreak for R to save the object without an error
# replace slashes in string
gsub(pattern="\"", replacement="/", x=path) # I have to put an extra quote in the pattern to avoid error, but this makes it not work.
Note that to avoid errors in this example, I had to save the path with a linebreak and there is an extra quote in the pattern for gsub. This is only a problem on Windows computers, but I need my package to work on Windows. Thanks in advance for suggestions.

Related

Rblogdown, unable to set file directory to D-drive, when launching local server [duplicate]

I run R on Windows, and have a csv file on the Desktop. I load it as follows,
x<-read.csv("C:\Users\surfcat\Desktop\2006_dissimilarity.csv",header=TRUE)
but the R gives the following error message
Error: '\U' used without hex digits in character string starting "C:\U"
So what's the correct way to load this file. I am using Vista
replace all the \ with \\.
it's trying to escape the next character in this case the U so to insert a \ you need to insert an escaped \ which is \\
Please do not mark this response as correct as smitec has already answered correctly. I'm including a convenience function I keep in my .First library that makes converting a windows path to the format that works in R (the methods described by Sacha Epskamp). Simply copy the path to your clipboard (ctrl + c) and then run the function as pathPrep(). No need for an argument. The path is printed to your console correctly and written to your clipboard for easy pasting to a script. Hope this is helpful.
pathPrep <- function(path = "clipboard") {
y <- if (path == "clipboard") {
readClipboard()
} else {
cat("Please enter the path:\n\n")
readline()
}
x <- chartr("\\", "/", y)
writeClipboard(x)
return(x)
}
Solution
Try this: x <- read.csv("C:/Users/surfcat/Desktop/2006_dissimilarity.csv", header=TRUE)
Explanation
R is not able to understand normal windows paths correctly because the "\" has special meaning - it is used as escape character to give following characters special meaning (\n for newline, \t for tab, \r for carriage return, ..., have a look here ).
Because R does not know the sequence \U it complains. Just replace the "\" with "/" or use an additional "\" to escape the "\" from its special meaning and everything works smooth.
Alternative
On windows, I think the best thing to do to improve your workflow with windows specific paths in R is to use e.g. AutoHotkey which allows for custom hotkeys:
define a Hotkey, e.g. Cntr-Shift-V
assigns it an procedure that replaces backslashes within your Clipboard with
slaches ...
when ever you want to copy paste a path into R you can use Cntr-Shift-V instead of Cntr-V
Et-voila
AutoHotkey Code Snippet (link to homepage)
^+v::
StringReplace, clipboard, clipboard, \, /, All
SendInput, %clipboard%
My Solution is to define an RStudio snippet as follows:
snippet pp
"`r gsub("\\\\", "\\\\\\\\\\\\\\\\", readClipboard())`"
This snippet converts backslashes \ into double backslashes \\. The following version will work if you prefer to convert backslahes to forward slashes /.
snippet pp
"`r gsub("\\\\", "/", readClipboard())`"
Once your preferred snippet is defined, paste a path from the clipboard by typing p-p-TAB-ENTER (that is pp and then the tab key and then enter) and the path will be magically inserted with R friendly delimiters.
Replace back slashes \ with forward slashes / when running windows machine
I know this is really old, but if you are copying and pasting anyway, you can just use:
read.csv(readClipboard())
readClipboard() escapes the back-slashes for you. Just remember to make sure the ".csv" is included in your copy, perhaps with this:
read.csv(paste0(readClipboard(),'.csv'))
And if you really want to minimize your typing you can use some functions:
setWD <- function(){
setwd(readClipboard())
}
readCSV <- function(){
return(readr::read_csv(paste0(readClipboard(),'.csv')))
}
#copy directory path
setWD()
#copy file name
df <- readCSV()
Replacing backslash with forward slash worked for me on Windows.
The best way to deal with this in case of txt file which contains data for text mining (speech, newsletter, etc.) is to replace "\" with "/".
Example:
file<-Corpus(DirSource("C:/Users/PRATEEK/Desktop/training tool/Text Analytics/text_file_main"))
I think that R is reading the '\' in the string as an escape character. For example \n creates a new line within a string, \t creates a new tab within the string.
'\' will work because R will recognize this as a normal backslash.
readClipboard() works directly too. Copy the path into your clipboard
C:\Users\surfcat\Desktop\2006_dissimilarity.csv
Then
readClipboard()
appears as
[1] "C:\\Users\\surfcat\\Desktop\\2006_dissimilarity.csv"
A simple way is to use python.
in python terminal type
r"C:\Users\surfcat\Desktop\2006_dissimilarity.csv"
and you'll get back
'C:\Users\surfcat\Desktop\2006_dissimilarity.csv'

How to write a function to change "\" to "/" in R

Firstly, I understand that "\" is an R escape character and also the file path separator on windows.
I know that it can be escaped by using either / or \.
I am developing a package and I want a function for the user to literally just be able to call it like:
makeFileLocationRCompatable("H:\Temp")
and for the function to return
"H:/Temp"
or
"H:\\Temp"
but it seems to be impossible in R due to the fact that \ escapes the following character.
I don't want my users to have to change the way they input the file path.
Any ideas?
You can use Rstudio snippetsaddin to convert the slash
download it from here.
devtools::install_github("sfr/RStudio-Addin-Snippets", type = "source")
Restart Rstudio.
Select the path or the code where slashes needs to be replaced.
Click on Addin -> select convert slash
It will reverse all slashes if the path is selected.
normalizePath from the base package might provide this functionality? (I cannot test on Windows myself; sorry if this is a moot proposal)
For example
normalizePath('H:\\Temp', winslash = '\\')
See also ?normalizePath

sparklyr iconv or remove non UTF-8 chars

I'm just getting into sparklr (and R actually) and slowly getting the hang of figuring out what works and what doesn't. Working on converting a straight R script to work with sparklyr. I've managed to replace grepl with regexp_replace and work out the differences in the regex formats..
I'm a bit stuck on this one tho...I am loading files (spark_read_json) that can contain non UTF-8 chars, and want to remove them.
The code that works to remove these chars in straight R is
fileline <- fileline %>% mutate(text = iconv(text, "", "UTF-8", sub=" "))
.. and this doesn't work with sparlyr. Looks like iconv isn't available.
I'm not sure what alternative to use for this. Hive doesn't appear to have an equivalent. And spark_read_json doesn't have an option like read_csv has...
There's a possible regex approach here:
Remove non-utf8 characters from string
But I was just wondering if there is something a little less involved already available...
Thanks

How to enter a character string verbatim in R? [duplicate]

I am looking for an efficient way to convert back slash to forward slash in R. Sometime I copy the link of the directory in Windows and I get something like this:
C:\Users\jd\Documents\folder\file.txt
How can I quickly change this to C:/Users/jd/Documents/folder/file.txt ? I cannot even read the above expression as character. It throws an error
"\u used without hex digits in character string starting ""C:\u".
I know TAB function in R helps to find the location fast, but was just wondering if there was any other work around. I could change the working directory to the location of folder also. I was just playing around and tried to convert backslash to forward slash and was not straight forward so asked this just because of curiosity.
In R, you've to escape the \ with \\ So, your path should be:
x <- "C:\\Users\\jd\\Documents\\folder\\file.txt"
To get that, you can do:
x <- readline()
then, at the prompt, paste your unmodified path (CTRL+V then ENTER)
Finally, to change \\ to / everywhere, you could use gsub, once again by escaping the \, but twice, as follows:
gsub("\\\\", "/", x)
# [1] "C:/Users/jd/Documents/folder/file.txt"
If you want the least number of keystrokes to convert backslashes when pasting paths, use an RStudio snippet defined as follows:
snippet pp
"`r gsub('"', "", gsub("\\\\", "/", readClipboard()))`"
Remember to preface the second line with a tab, not multiple spaces for the snippet to work.
Then type pp, TAB, ENTER and the text on your clipboard is pasted, backslashes replaced with forward slashes and surrounded by quotes.
Here is the steps I usually take to copy file paths to RStudio once the above snippet has been defined:
Navigate to file path in explorer.
If copying a file path then: Shift + Right click on file, then click Copy as path.
If copying a folder path then: Alt + d, Ctrl + c.
Change window to RStudio and focus in R script where you want to paste the path.
pp, TAB, ENTER to paste into RStudio and convert backslashes to forward slashes.
I use Path Copy Copy, which is a plug-in to Windows that allows you to create custom copy commands when you right-click a file/folder in Windows. So my right-click menu has "Copy Full Path with Forward Slash" as an option, which copies the file/folder with forward slashes. I am guessing it saves me days every year from manually changing slashes to R's format.
I like to use the RStudio add-in snippetsaddin which has the function 'Convert slash':
It will reverse all slashes either in the selected block(s) of code, or if there is no selection (or only whitespace is selected), it will reverse all slashes in the clipboard and paste it to the current cursor(s) position(s).
Addins are isntalled like a package. To install this one, do this:
devtools::install_github("sfr/RStudio-Addin-Snippets", type = "source")
If I understand correctly, you do want to get rid of the string editing. In order to be able to use gsub you would have to change all the \ to \\ manually first. So, why not just change \ to / in first place?
If you have the string in the clipboard you can use
x=scan("clipboard",what="string")
This gives
"C:\\Users\\jd\\Documents\\folder\\file.txt"
That is, it converts all \ to \\ automatically.
I know - not very handy, but the only way I know to get around the editing.
Here is a one step method of converting the address from the clipboard
x <- gsub ( "\\\\", "/", readClipboard () )
autohotkey program:
^+v::
StringReplace, clipboard, clipboard, \,/,All
send %clipboard%
after control+c the file path, use control + shift + v to paste
A solution without a snippet defintion is
writeClipboard(gsub("\\\\", "/", readClipboard()))
R has the inbuilt r"(C:\myfolder\)" command which converts backslashes in a string to double backslashes.
x <- r"(C:\myfolder\)"
print(x)
"C:\\myfolder\\"
Only problem is that it can't take a variable and can only take a typed string
I think the best way to get rid of the hassle is to find the file in Rstudio in the right panel. And then click "more" and click "Set as Working Directory". Then you will see in the console "setwd(...)". You can copy this to your code.
My method is the same as what #pluke stated.
This is how I set my working directory:
x <- r"(C:\myfolder\)"
setwd(x)

Efficiently convert backslash to forward slash in R

I am looking for an efficient way to convert back slash to forward slash in R. Sometime I copy the link of the directory in Windows and I get something like this:
C:\Users\jd\Documents\folder\file.txt
How can I quickly change this to C:/Users/jd/Documents/folder/file.txt ? I cannot even read the above expression as character. It throws an error
"\u used without hex digits in character string starting ""C:\u".
I know TAB function in R helps to find the location fast, but was just wondering if there was any other work around. I could change the working directory to the location of folder also. I was just playing around and tried to convert backslash to forward slash and was not straight forward so asked this just because of curiosity.
In R, you've to escape the \ with \\ So, your path should be:
x <- "C:\\Users\\jd\\Documents\\folder\\file.txt"
To get that, you can do:
x <- readline()
then, at the prompt, paste your unmodified path (CTRL+V then ENTER)
Finally, to change \\ to / everywhere, you could use gsub, once again by escaping the \, but twice, as follows:
gsub("\\\\", "/", x)
# [1] "C:/Users/jd/Documents/folder/file.txt"
If you want the least number of keystrokes to convert backslashes when pasting paths, use an RStudio snippet defined as follows:
snippet pp
"`r gsub('"', "", gsub("\\\\", "/", readClipboard()))`"
Remember to preface the second line with a tab, not multiple spaces for the snippet to work.
Then type pp, TAB, ENTER and the text on your clipboard is pasted, backslashes replaced with forward slashes and surrounded by quotes.
Here is the steps I usually take to copy file paths to RStudio once the above snippet has been defined:
Navigate to file path in explorer.
If copying a file path then: Shift + Right click on file, then click Copy as path.
If copying a folder path then: Alt + d, Ctrl + c.
Change window to RStudio and focus in R script where you want to paste the path.
pp, TAB, ENTER to paste into RStudio and convert backslashes to forward slashes.
I use Path Copy Copy, which is a plug-in to Windows that allows you to create custom copy commands when you right-click a file/folder in Windows. So my right-click menu has "Copy Full Path with Forward Slash" as an option, which copies the file/folder with forward slashes. I am guessing it saves me days every year from manually changing slashes to R's format.
I like to use the RStudio add-in snippetsaddin which has the function 'Convert slash':
It will reverse all slashes either in the selected block(s) of code, or if there is no selection (or only whitespace is selected), it will reverse all slashes in the clipboard and paste it to the current cursor(s) position(s).
Addins are isntalled like a package. To install this one, do this:
devtools::install_github("sfr/RStudio-Addin-Snippets", type = "source")
If I understand correctly, you do want to get rid of the string editing. In order to be able to use gsub you would have to change all the \ to \\ manually first. So, why not just change \ to / in first place?
If you have the string in the clipboard you can use
x=scan("clipboard",what="string")
This gives
"C:\\Users\\jd\\Documents\\folder\\file.txt"
That is, it converts all \ to \\ automatically.
I know - not very handy, but the only way I know to get around the editing.
Here is a one step method of converting the address from the clipboard
x <- gsub ( "\\\\", "/", readClipboard () )
autohotkey program:
^+v::
StringReplace, clipboard, clipboard, \,/,All
send %clipboard%
after control+c the file path, use control + shift + v to paste
A solution without a snippet defintion is
writeClipboard(gsub("\\\\", "/", readClipboard()))
R has the inbuilt r"(C:\myfolder\)" command which converts backslashes in a string to double backslashes.
x <- r"(C:\myfolder\)"
print(x)
"C:\\myfolder\\"
Only problem is that it can't take a variable and can only take a typed string
I think the best way to get rid of the hassle is to find the file in Rstudio in the right panel. And then click "more" and click "Set as Working Directory". Then you will see in the console "setwd(...)". You can copy this to your code.
My method is the same as what #pluke stated.
This is how I set my working directory:
x <- r"(C:\myfolder\)"
setwd(x)

Resources