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

前端 未结 11 1934
我寻月下人不归
我寻月下人不归 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:35

    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'

    0 讨论(0)
  • 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% 
    
    0 讨论(0)
  • 2020-11-28 19:40

    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"
    
    0 讨论(0)
  • 2020-11-28 19:42

    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()
    
    0 讨论(0)
  • 2020-11-28 19:43

    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 \\

    0 讨论(0)
提交回复
热议问题