使commandargs以逗号分隔或解析空格 [英] making commandargs comma delimited or parsing spaces

查看:207
本文介绍了使commandargs以逗号分隔或解析空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用命令行参数从命令行运行R.这包括传递一些文件路径作为脚本内部使用的参数.大部分时间都可以使用,但是有时路径中有空格,而R无法理解.

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

R抛出一个文件说

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

因此,显然我的单引号还不足以告诉R将引号内的所有内容都用作参数值.我在想这意味着我应该找到一种使用逗号来分隔--args的方法,但是我找不到一种方法来做到这一点.我敢肯定这很简单,但是我在文档中什么都没找到.

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.

当前脚本非常基础:

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)

如果相关,我正在使用Windows,但这似乎不是cmd提示问题.

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

推荐答案

使用eval(parse())可能不是解析命令行参数的最佳,最有效的方法.我建议使用 optparse 之类的程序包为您解析.解析命令行参数已解决,无需重新实现.我可以想象这可以解决您的问题.虽然,开始时路径名中的空格是个坏主意.

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]

这避免了我认为引起问题的eval(parse.最后,您可以尝试像这样逃脱空间:

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"

您也可以尝试RscriptR CMD BATCH似乎不如Rscript受欢迎.

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

这篇关于使commandargs以逗号分隔或解析空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆