Search code examples
rcronrscript

Crontab R script failing due to import function (Rstudio is closed)


I am trying to run a Rscript using crontab with Rstudio closed and i am getting the following error in the log when the script is ran:

Warning message:
package ‘dplyr’ was built under R version 4.0.2 
Error in import("~/Desktop/R/Projects/TestFile.csv",  : 
  could not find function "import"
Execution halted

From my limited knowledge of crontab functionality it is my understanding that the 'import' function can only work with Rstudio open. Is there a way to get around this such as using an alternative function that imports a file that can be read using crontab?

Note: The script works when run in Rstudio.

EDIT:

Crontab instruction:

if (!require("cronR")) {
  install.packages("cronR")
  library(cronR)
}

cron_clear(ask=FALSE)

f <- "~/Desktop/R/Projects/MyRCode.R"
cmd <- cron_rscript(f)
cmd

cron_add(cmd, frequency = "daily", id = "test", at = "16:30")

Rscript:

library("miniUI")
library("shinyFiles")
library(quantmod)

if (!require("httr")) {
  install.packages("httr")
  library(httr)
}

if (!require("jsonlite")) {
  install.packages("jsonlite")
  library(jsonlite)
}

if (!require("gsubfn")) {
  install.packages("gsubfn")
  library(gsubfn)
}

if (!require("rjson")) {
  install.packages("rjson")
  library(rjson)
}

if (!require("RJSONIO")) {
  install.packages("RJSONIO")
  library(RJSONIO)
}

library(dplyr)

rio_csv <- import("~/Desktop/R/Projects/TestFile.csv",stringsAsFactors=FALSE)
df <- data.frame("Ticker" = rio_csv[,1],"Amount" = rio_csv[,3], "Shares" = rio_csv[,6],"Average"= rio_csv[,8])

write_json(df,"~/Desktop/R/Projects/JSONFile.json")

Solution

  • function import is from the rio package. Your automated script fails because you did not load that package rio as in library(rio). This could not even have worked in RStudio itself neither if you did not load package rio.