如何使用 OpenCPU 运行 一个 custom.R 脚本

How to run a custom.R script using OpenCPU

我有一个看起来应该很简单的问题,但它似乎没有在 OpenCPU API 文档中解决。我已经很好地设置和配置了我的 OpenCPU 服务器,我可以浏览 http://localhost/ocpu/test/ 并且可以很好地探索一切。在浏览文档时,我可以看到 运行 通过一个包很容易,但是有没有办法在我的服务器上 运行 一个简单的 .R 文件而不必将它变成一个包?我宁愿不必将它变成一个包来测试它。任何人都知道这是否可行,如果可行,正确的是什么 API?

没有。来自OpenCPU FAQ #2: An OpenCPU app is an R package which includes some web page(s) that call the R functions in the package using the OpenCPU API (emphasis mine). I strongly encourage you to learn to make packages, even if just for random functions. Hadley's devtools package (among others) make building packages much easier; if you need help, his r-pkgs docs都挺好的。

有一种方法可以 运行 单个 R 脚本。

不幸的是,它有一个限制,即您只能在 R 脚本中使用双引号或单引号。这是使用单引号的示例:

# Make test script. DO NOT USE DOUBLE-QUOTES inside the script.
echo "a = c('10', '20')" > myscript.r

# Encode it for transfer.
SCRIPT_ENCODED="$(urlencode "$(cat myscript.r)" | sed -r 's/%0A/\n/g')"

# Save the script on the server.
RES1=$(curl -s "localhost:8004/ocpu/library/base/R/write" \
    -H "multipart/form-data" \
    -d "x=\"$SCRIPT_ENCODED\"" \
    -d "file='script.r'")

# Execute the script on the server.
TMP_TOKEN1=$(echo $RES1 | sed -r 's/^.*tmp\/(\w+).*$//')
RES2=$(curl -s "localhost:8004/ocpu/tmp/$TMP_TOKEN1/files/script.r" -X POST)

# View the results.
echo $RES2
TMP_TOKEN2=$(echo $RES2 | sed -r 's/^.*tmp\/(\w+).*$//')
curl "localhost:8004/ocpu/tmp/$TMP_TOKEN2/R/a/print"