如何在 R 中获取托管在 gitlab 上的远程文件?

How to source a remote file hosted on gitlab in R?

我在 Gitlab 上有一个内部存储库。

在我的 R 脚本中,我想 source 来自该内部存储库的 .R 文件。

通常我可以使用以下代码获取公开可用的 R 脚本

source("public-path-to-file")

但是当我尝试使用私有文件执行此操作时,我得到:

Error in source("") : 
  :1:1: unexpected '<'
1: <
    ^

我找到了一种至少可以完成任务的 hacky 方法:

首先,您需要创建一个具有 api 访问权限的私人令牌。然后就可以直接调用gitlab的API获取文件

代码:

cmd <- "curl -s --header 'PRIVATE-TOKEN: <your private token for gitlab with api access>' '<full gitlab link of the raw file that you want to source>'" # you directly access the API with your private token

output <- system(cmd, intern=TRUE) # capturing the output of the system call

writeLines(output, "functions.R") # creating a temporary file which contains the output of the API call

source("functions.R") # Sourcing the file the usual way

file.remove("functions.R") # removing the temporary file for housekeeping

解释:

我们使用系统命令 curl 通过 GET 请求直接调用 API。

然后通过R调用系统命令,捕获结果。

然后您可以创建一个包含相应内容的临时文件,并像往常一样获取它。希望这可以帮助某人