File path issues in R using Windows (“Hex digits i

2020-01-25 12:42发布

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

11条回答
仙女界的扛把子
2楼-- · 2020-01-25 12:57

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)
}
查看更多
Bombasti
3楼-- · 2020-01-25 12:58

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"
查看更多
Juvenile、少年°
4楼-- · 2020-01-25 13:07

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.

查看更多
在下西门庆
5楼-- · 2020-01-25 13:11

Replace back slashes \ with forward slashes / when running windows machine

查看更多
爷的心禁止访问
6楼-- · 2020-01-25 13:12

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"))
查看更多
倾城 Initia
7楼-- · 2020-01-25 13:15

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.

查看更多
登录 后发表回答