rwindowsclipboard

Getting filename from clipboard in R


In R, is it possible to get the full path and filename (in Windows) of a file copied to clipboard?

Background is that I have several large Excel files containing data I'd like to process in R. The filesystem is relatively unstructured, so getting the paths/filenames of these files programatically is not really an option. I don't want to open the Excel files for copy-pasting data into R either, because opening large Excels takes a lot of time. So I am looking for an option where I can navigate to a file using the file explorer, copy the file to clipboard, and then reading in the content of the file into R, which I could set up if I can extract file name and path.

Both utils::readClipboard() and clipr::read_clip() return NULL if a file is copied to clipboard.


Solution

  • Expanding upon Konrad's comments, you can get the file path from a file copied to the clipboard using readClipboard() with formats 49158 (short filename) and 49159 (long filename). As an example, after copying the R executable to the clipboard:

    # Short filename
    readClipboard(format = "49158", raw = TRUE) |> 
      rawToChar()
        
    [1] "C:\\PROGRA~1\\R\\R-44~1.1\\bin\\x64\\R.exe"
    
    # Long filename
    readClipboard(format = "49159", raw = TRUE) |> 
        rawToChar(multiple = TRUE) |> 
        paste0(collapse = "")
    
    [1] "C:\\Program Files\\R\\R-4.4.1\\bin\\x64\\R.exe"