R编程:调用R程序,使用png()函数时收到错误

时间:2020-07-26 08:29:54

标签: r linux

下面是用于调用Rscript的Linux Shell脚本。

#!/bin/bash

folder=$(date +"%d-%m-%Y-%R")
echo $folder
mkdir /home/nigel/Desktop/cron/"$folder"
Rscript /home/nigel/Desktop/cron/var.R $folder

下面是Rscript

args<-commandArgs()
a<-args
print(args)

date_path=paste("/home/nigel/Desktop/cron/",a,"/file.png",sep = "")

#read the data and create the histogram, thens save it

data = read.csv("/home/nigel/Desktop/cron/Customer.csv", header = TRUE)
png(a,height = 1000,width = 1000)
hist(data$Age)
graphics.off()
print(date_path)
print("Ended well")

我在执行Shell脚本时收到以下错误。

(base) nigel@nigel:~/Desktop/cron$ ./var.sh
26-07-2020-12:10
[1] "/usr/lib/R/bin/exec/R"                
[2] "--slave"                              
[3] "--no-restore"                         
[4] "--file=/home/nigel/Desktop/cron/var.R"
[5] "--args"                               
[6] "26-07-2020-12:10"                     
Error in plot.new() : could not open file '/usr/lib/R/bin/exec/R'
Calls: hist -> hist.default -> plot -> plot.histogram -> plot.new
Execution halted

请注意,如果我在Rscript中注释以下代码行,则不会收到错误消息。

png(a,height = 1000,width = 1000)
hist(data$Age)
graphics.off()

即使我用grap.off()替换了graphics.off(),我仍然收到错误消息

1 个答案:

答案 0 :(得分:0)

默认情况下,commandArgs返回R可执行文件的名称和路径。 因此,它出现在错误消息/usr/lib/R/bin/exec/R中。 可以通过commandArgs(trailingOnly = TRUE)来避免。

我在RStudio中对其进行了测试:

commandArgs()
# [1] "RStudio"       "--interactive"

commandArgs(trailingOnly = TRUE)
# character(0)

因此解决方案是使用此行获取png文件名:

a = commandArgs(trailingOnly = TRUE)