Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making commandargs comma delimited or parsing spaces

I'm trying to run R from the command line using command line arguments. This includes passing in some filepaths as arguments for use inside the script. It all works most of the time, but sometimes the paths have spaces in and R doesn't understand.

I'm running something of the form:

R CMD BATCH --slave "--args inputfile='C:/Work/FolderWith SpaceInName/myinputfile.csv' outputfile='C:/Work/myoutputfile.csv'" RScript.r ROut.txt

And R throws out a file saying

Fatal error: cannot open file 'C:\Work\FolderWith': No such file or directory

So evidently my single quotes aren't enough to tell R to take everything inside the quotes as the argument value. I'm thinking this means I should find a way to delimit my --args using a comma, but I can't find a way to do this. I'm sure it's simple but I've not found anything in the documentation.

The current script is very basic:

ca = commandArgs(trailingOnly=TRUE)
eval(parse(text=ca))
tempdata = read.csv(inputFile)
tempdata$total = apply(tempdata[,4:18], 1, sum)
write.csv(tempdata, outputFile, row.names = FALSE)

In case it's relevant I'm using windows for this, but it seems like it's not a cmd prompt problem.

like image 961
user1878693 Avatar asked Dec 05 '12 11:12

user1878693


1 Answers

Using eval(parse()) is probably not the best and most efficient way to parse command line arguments. I recommend to use a package like the optparse to do the parsing for you. Parsing command line args has already been solved, no need to reimplement this. I could imagine that this solves your problems. Although, spaces in path names are a bad idea to begin with.

Alternatively, you could take a very simple approach and pass the arguments like this:

R CMD BATCH --slave arg1 arg2

Where you can retrieve them like:

ca = commandArgs(TRUE)
arg1 = ca[2]
arg2 = ca[3]

This avoids the eval(parse which I think is causing the issues. Finally, you could try and escape the space like this:

R CMD BATCH --slave "C:/spam\ bla"

You could also give Rscript a try, R CMD BATCH seems to be less favored than Rscript.

like image 154
Paul Hiemstra Avatar answered Sep 28 '22 08:09

Paul Hiemstra