File path issues in R using Windows (“Hex digits in character string” error)

前端 未结 11 2040
我寻月下人不归
我寻月下人不归 2020-11-28 19:06

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=T         


        
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 19:36

    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% 
    

提交回复
热议问题