我有以下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脚本中调用时,则给出错误。
错误在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
And the [ ... ]
operator is now obsoleted, use [[ ... ]]
instead, like this:
if [[ $option == option1 ]]; then
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句