1

Best

I've a R-script, which is located on my amazon S3 Bucket. What I want to do is, I would like to create a python 2.7 programm which can run R-scripts, (which are located and streamed via a S3-bucket). To do this, i would like to use the rpy2 library (without downloading the script itself temp. (thus : s3.get_object() unstead of s3.download_file() )).

Main question:

how do I load, the R-script into R, without downloading it. because :

def __init__(self, r_script):
    self._r = robjects.r
    self._r.source(r_script.read())

or

def __init__(self, r_script):
    self._r = robjects.r
    self._r.source(r_script)

Doesn't work ... because it is not a location-string but already the code itself

Here is the content of my test script :

rm(list = ls())

test1<- function(){}

test2<- function(){}

test3<- function(){}

execute<- function(){

  a <- c(1,2,3)
  c <- c(1,2,3)
  b <- c(1,2,3)

  r <- data.frame(a,b,c)

  return(r)
}
  • Actually, I think it would be already fine, if I could parse a big block of code, like the above, as a R script. (because, r_script.read(), is ~ a big string (I think))

Kind regards

Dieter
  • 2,499
  • 1
  • 23
  • 41
  • Curious, why not have Python call the R script via command line with *Rscript.exe*? – Parfait Oct 18 '16 at 16:20
  • because, there will be more +/- 15 interactions between the R and python environment. Python will call data from DynamoDB, or S3 and parse it to R, which will receive it knwoledge back, which can be stored again etc, :) – Dieter Oct 18 '16 at 16:22
  • Got it! A very important tidbit to include. – Parfait Oct 18 '16 at 17:03

1 Answers1

2

rpy2 can let you parse a string as R code before evaluating it, and this is used in an helper class making a Python namespace out of the string containing R code (See Calling Custom functions from Python using rpy2).

from rpy2.robjects.packages import STAP
mymodule = STAP(r_script, "mymodule")

# call a function
mymodule.execute()

Note: I am seeing rm(list=ls)() at the beginning of your R script. If your R script is meant to be a library it should not assume anything about the frame in which it is executed. To help with that, the class STAP above will execute the R code in a new enviroment (not R's GlobalEnv).

Community
  • 1
  • 1
lgautier
  • 11,363
  • 29
  • 42