How to get a path string from R that I can paste immediately into Windows

443 views Asked by At

Let's say I have a Windows path: "R:\data\state-capitals\final\"

If I add "\", I can use the path inside the R console (on a Windows system).

mypath = "R:\\data\\state-capitals\\final\\";

If I have the R console form

mypath = "R:/data/state-capitals/final/";
normalizePath(mypath);
# "R:\\data\\state-capitals\\final"

How do I go the other way? How do I get R to print something to the screen that I can copy, click Win-R and paste to use File explorer to go to the location ... I want it to print something to the screen (and also the clipboard).

I get that nchar("\\") is one, but that doesn't allow me to minimize string manipulation... I want R to output something like: R:\data\state-capitals\final\ so I can copy/paste back into the Windows environment.

And a solution that keeps the trailing slash would be nice.


Based on @Linh, here are a few functions ...

https://gist.github.com/MonteShaffer/8555de33cec2b6ffff81c268bcccc041

# https://stackoverflow.com/questions/64476043/
# https://stackoverflow.com/questions/1189759/
convertDirectoryR.toWin = function(myDir = getwd())  # "R:/data/state-capitals/final/"
  {
  cat( normalizePath(myDir) );
    writeClipboard( normalizePath(myDir) ); # R:\data\state-capitals\final\
  }

openDirectoryR.inWin = function(myDir = getwd())  # "R:/data/state-capitals/final/"
  {
  cmd = paste("explorer",  gsub('/', '\\\\', myDir, fixed=TRUE ) );
  suppressWarnings( shell( cmd ) );        # R:\data\state-capitals\final\
  }

convertDirectoryWin.toR = function(myDir = readClipboard()) # # R:\data\state-capitals\final\
  {
  gsub('\\', '/', myDir, fixed=TRUE );   # "R:/data/state-capitals/final/"
  }

Besides paste, how can I read winDir in? Using convertDirectoryWin.toR?

1

There are 1 answers

0
Linh On BEST ANSWER

I think you can use cat()

mypath = "R:/data/state-capitals/final/"
cat(normalizePath(mypath))
# "R:\data\state-capitals\final\