我有以下R脚本,我已经添加了注释,以便为我想要实现的汽车制作一个简单示例:
#!/usr/bin/env Rscript
# the arguments come in this way:
# args[1] is a file containing the maximum speeds of different cars (one per line)
# args[2] is the title that the plot will have
# args[3] contains the horsepower of the engine of the first car in args[1] (the lowest)
# args[4] contains the horsepower of the engine of the last car in args[1] (the highest)
# NOTE1: the speeds in args[1] must be listed starting from the car
# with the lowest horsepower to the car with the highest horsepower
# NOTE2: in args[1], a car must differ from the next one by 1 horsepower, i.e., if
# there are 5 speeds, and the horsepower of the first car in the file is 30, then the
# the horsepower of the second one must be 31, the third one 32, .... the fifth one must
# be 34.
args<-commandArgs(TRUE)
# creating the vector with the horsepower of each car
horsepowers = numeric()
for (i in args[3]:args[4]) {
horsepowers = c(horsepowers,i)
}
# reading file with speeds and getting vector with speeds
speeds <- read.csv(file=args[1],head=FALSE,sep="\n")$V1
# creating plot with speeds in previous vector
outputTitle = gsub(" ","", args[2] , fixed=TRUE)
pdf(paste(outputTitle, ".pdf", sep = ""))
plot(horsepowers, speeds, type="o", col="red", xlab="horsepowers", ylab="speeds")
# giving a title to the plot
title(main=args[2], col.main="Black")
我有一个名为myFile
的示例文件,速度为5辆,看起来像这样
150
156
157
161
164
并且假设第一辆汽车的马力为30,这样可以使最后一辆汽车的马力达到34(请记住,第一速度对应于马力最低的汽车,第二速度对应于汽车的最低速度。最低马力,等等;并且汽车必须相差1马力,否则脚本中的for循环没有意义)。因此,如果我在命令行中运行脚本,如下所示:
./myPlotter.R myFile "My Title" 30 34
它工作正常并制作情节(我裁剪了y标签,x标签和标题只是因为它们与上面的汽车示例不匹配但是使用的脚本是相同的,我只是更改了变量名称对于汽车示例):
但是,从以下bash脚本调用时:
#!/bin/bash
while getopts ":a:1:2:3:4" arg; do
case "$arg" in
a)
option=$OPTARG
;;
1)
fileWithSpeeds=$OPTARG
;;
2)
titleOfGraph=$OPTARG
;;
3)
lowestHP=$OPTARG
;;
4)
highestHP=$OPTARG
;;
esac
done
# I do not think that this if statement makes any difference for this example
# but I left it there just in case
if [ $option == "option1" ]; then
./myPlotter.R $fileWithSpeeds $titleOfGraph $lowestHP $highestHP
fi
以这种方式:
./bashPlot.sh -a option1 -1 myFile -2 "My Title" -3 30 -4 34
我收到以下错误:
Error in args[3]:args[4] : NA/NaN argument
Execution halted
造成这种情况的原因是什么?
总结:我有一个R脚本在从命令行调用时工作正常,但是当从带有getopts的参数的bash脚本调用时会出错。
答案 0 :(得分:2)
错误在getots
字符串中,而不是:
while getopts ":a:1:2:3:4" arg; do
应该是这样的:
while getopts "a:1:2:3:4:" arg; do
您可以通过回显执行R脚本的命令来查看问题:
echo "./myPlotter.R $fileWithSpeeds $titleOfGraph $lowestHP $highestHP"
./myPlotter.R $fileWithSpeeds $titleOfGraph $lowestHP $highestHP
您可以从输出中看到$highestHP
参数始终为空白。
这里不需要双引号:
if [ $option == "option1" ]; then
[ ... ]
运算符现已废弃,请改用[[ ... ]]
,如下所示:
if [[ $option == option1 ]]; then