Jason Tham
Jason Tham

Reputation: 123

How to run a custom.R script using OpenCPU

I have a question that seems like it should be simple, however it doesn't seem to be addressed in the OpenCPU API documentation. I have setup and configured my OpenCPU server just fine, I can browse http://localhost/ocpu/test/ and I can explore everything just fine. When going through the documentation I can see it is quite easy to run through a package, but is there a way to just run a simple .R file on my server without having to turn it into a package? I'd rather not have to turn it into a package to test it. Anyone know if this is possible and if so what's the correct API?

Upvotes: 3

Views: 1941

Answers (2)

Akuukis
Akuukis

Reputation: 719

There is a way to run single R script.

Unfortunally it has a limitation that you can use only either double-quotes or single-quotes in the R script. Here's example that works with single-quotes:

# 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+).*$/\1/')
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+).*$/\1/')
curl "localhost:8004/ocpu/tmp/$TMP_TOKEN2/R/a/print"

Upvotes: 1

r2evans
r2evans

Reputation: 160952

No. From the 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 are quite good.

Upvotes: 3

Related Questions