R Project Import Error - r

I'm brand new to R Project.
I've tried to import using the file path, and no matter what path way I use I get this same error. It says the back slash and the first character after it is an unrecognized escape.
I can import files by using the file.choose() function and manually navigating to my file, but I need to be able to use the file path method in code so that I can run multiple iterative steps without having to be there to choose the file at every point.
Does anyone have any ideals on why this error might occur? Is there anything wrong with my code? Is there some kind of configuration I need to do?
Thanks.
Data1 <- read.table(file="\Head-Location-001\MarketingAnalysis\Competitive Intelligence\Stick Rate\Last week\Test.cvs" sep",", header=TRUE)
Error: '\C' is an unrecognized escape in character string starting ""\fknp-sfs-001\fknmktanlys\
Import Error

replace all the \ with \\.
it's trying to escape the next character in this case the C so to insert a \ you need to insert an escaped \ which is \\
or
Replacing them with / works as well

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

Remove line feed in CSV using Unix script

I have a CSV file and I want to remove the all line feeds (LF or \n) which are all coming in between the double quotes alone.
Can you please provide me an Unix script to perform the above task. I have given the input and expected output below.
Input :
No,Status,Date
1,"Success
Error",1/15/2018
2,"Success
Error
NA",2/15/2018
3,"Success
Error",3/15/2018
Expected output:
No,Status,Date
1,"Success Error",1/15/2018
2,"Success Error NA",2/15/2018
3,"Success Error",3/15/2018
I can't write everything for you, as I am not sure about your system as well as which bash version that is running on it. But here are a couple of suggestions that you might want to consider.
https://www.unix.com/shell-programming-and-scripting/31021-removing-line-breaks-shell-variable.html
https://www.unix.com/shell-programming-and-scripting/19484-remove-line-feeds.html
How to remove carriage return from a string in Bash
https://unix.stackexchange.com/questions/57124/remove-newline-from-unix-variable
Remove line breaks in Bourne Shell from variable
https://unix.stackexchange.com/questions/254644/how-do-i-remove-newline-character-at-the-end-of-file
https://serverfault.com/questions/391360/remove-line-break-using-awk

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