当要运行的文件位于不同的文件夹中时,如何在R中应用source()函数?

How to apply the source() function in R when the files to run are in different folders?

提问人:Hotshot 提问时间:11/13/2023 更新时间:11/20/2023 访问量:26

问:

我有两个 R 脚本(Script1.R 和 Script2.R),供不同的人用于数据分析。但是,这些脚本非常复杂,并且对用户不太友好。因此,我想创建另一个脚本,该脚本可用于运行其他两个脚本并确定特定的值和目录。 为此,我想使用该函数。source()

我当前的代码看起来或多或少是这样的:

#Data
individual_direction <-"C:/user/User1/Desktop/Data"

#Script 1
direction_script1 <- "SERVERNAME/userX/Team/R/XXX"

#Script 2
direction_script2 <- "SERVERNAME/userX/Team/R/YYY"

#Running the script using the directory mentioned above
source("SERVERNAME/userX/Team/R/XXX/Script1.R")

#Merging the newly created files according to their column or row
source("SERVERNAME/userX/Team/R/YYY/Script2.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 'direction_script1/Script1.R': No 
such file or directory

但是,当我输入整个目录(例如,)时,脚本运行没有任何问题。source("SERVERNAME/userX/Team/R/XXX/Script1.R")

你能帮我解决这个问题吗? 非常感谢您提前提供的帮助!

R 文件 目录 连接

评论

4赞 Limey 11/13/2023
我认为,从长远来看,与其采用你要求的方法,不如资助一个更复杂的解决方案:例如,编写一个包或使用某种中央代码存储库。采购存储在用户目录中的文件,这些文件没有信息,硬编码的文件名,只会让我所有的警告标志猛烈挥舞。

答:

1赞 MrFlick 11/20/2023 #1

您正在定义,但随后您没有在示例中使用它。如果你刚刚跑direction_script1

source("direction_script1/Script1.R") 

这样就不会展开变量名称。这只是一个字面字符串。这与

source("SERVERNAME/userX/Team/R/XXX/Script1.R")

为了将路径与变量组合在一起,您可以使用该函数来构建正确的路径。file.path

source(file.path(direction_script1, "Script.R"))