简体   繁体   中英

Spaces in paths in batch mode R

I'm trying to get an R script to run from a batch file so it can be nice and clean for other users. Currently, you drag and drop a CSV file onto the batch file and it passes the file name to the R script for input.

When there's a space in the file path/name it works fine in RStudio but causes problems when I call it from the batch file. When I do that it tries to open the path before the space.

I've tried to reformat the file path from within R by using shortPathName(inputPath) and by replacing spaces with "\\ " but it doesn't seem to work.

At the moment, the script is launched with

    "%~dp0\R-3.6.0\bin\R.exe" CMD BATCH "--args %~1" "%~dp0\Script.R"

with the script containing

    args <- commandArgs(TRUE)
    inputPath <- args[1]
    inputPath <- shortPathName(inputPath)
    inputData <- read.csv(inputPath)

It runs fine from within RStudio but crashes when launched from the batch producing this error message in the output file:

Error in file(file, "rt") : cannot open the connection
Calls: read.csv -> read.table -> file
In addition: Warning message:
In file(file, "rt") :
cannot open file ' file path up to the space ': No such file or directory
Execution halted

By no means a R expert, but I'd try

%~dp0\R-3.6.0\bin\R.exe" CMD BATCH "--args %~s1" "%~dp0\Script.R"

The %~s1 should supply the short filename as the argument.

After trying several formulations of the batch file and some debugging, I found that the batch file was passing the first part of the file before the space as the first argument.

After finding that the use of R in CMD BATCH mode is no longer advisable so switched to running using Rscript mode as

    "%~dp0\R-3.6.0\bin\Rscript.exe" --vanilla "%~dp0\Script.R" "%~1"

This allowed for the argument to be passed to R with "", and hence with the space. Since v3.5.1, R accepts file paths with spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM