我有一个'R'文件,它从数据库中插入读取数据,进行一些计算,然后将数据重新插入表中。
在我执行脚本之前,我运行'Source',如下所示..
我想使用Windows任务计划程序自动安排此脚本运行。我正在按照指南https://trinkerrstuff.wordpress.com/2015/02/11/scheduling-r-tasks-via-windows-task-scheduler/ - 创建.BAT文件时,它应该类似于:
echo off
CMD BATCH C:\PATHNAME\RSCRIPT.R
我应该在这里插入什么以确保它首先运行'Source'?
在R代码中我有
在我的代码中:
#use a relative path to locate our common utilities file and source it
source("..//R-Utilities//Utilities.R")
# use check_install_package function from Utilities.R to install and load
packages
check_install_package("lubridate")
check_install_package("plyr")
check_install_package("dplyr")
check_install_package("dtplyr")
check_install_package("ISOweek")
check_install_package("stringi")
check_install_package("RODBC")
#give us access to the library of functions this script uses
source("CTB_functions.R")
但是我需要在运行整个代码之前单击源按钮,否则我会收到错误(如下所示)。
> #this automatically sets the working directory to be where this file is
> setwd(getSrcDirectory(function(x) {x}))
Error in setwd(getSrcDirectory(function(x) { :
cannot change working directory
>
> #use a relative path to locate our common utilities file and source it
> source("../R-Utilities/Utilities.R")
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file '../R-Utilities/Utilities.R': No such file or directory
>
> # use check_install_package function from Utilities.R to install and load
packages
> check_install_package("lubridate")
Error: could not find function "check_install_package"
> check_install_package("plyr")
Error: could not find function "check_install_package"
> check_install_package("dplyr")
Error: could not find function "check_install_package"
> check_install_package("dtplyr")
Error: could not find function "check_install_package"
> check_install_package("ISOweek")
Error: could not find function "check_install_package"
> check_install_package("stringi")
Error: could not find function "check_install_package"
> check_install_package("RODBC")
Error: could not find function "check_install_package"
>
> #give us access to the library of functions this script uses
> source("CTB_functions.R")
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file 'CTB_functions.R': No such file or directory
答案 0 :(得分:1)
鉴于你的脚本,不需要先点击“Source”按钮:事实上,它会执行你的脚本两次。
关于脚本的一些事项:
CMD BATCH C:\PATHNAME\RSCRIPT.R
R
前面缺少CMD BATCH
。但是,您应该使用Rscript.exe
代替R CMD BATCH
。这是一个现代的替代品。
source("..//R-Utilities//Utilities.R")
不需要双斜线:单斜线工作。
source("../R-Utilities/Utilities.R")
更基本的是,以这种方式使用source
可能会由于几个缺点(例如循环包含,相对路径等)而迅速变得复杂且容易出错。实现这一目标的更好方法是通过<modules>包,它为source
函数提供了极大改进的替代,这似乎非常适合您的用例。
特别是,您的脚本可能无效:source
找不到文件R-Utilities/Utilities.R
和CTB_functions.R
,因为它会搜索相对于当前工作目录的文件,而不是相对于脚本目录。使用