Search code examples
pythonrnestedrpy2

Calling nested R script from python using rpy2


I have 2 separate R scripts such as func1.R and func2.R. Both are functions which receive inputs and return outputs e.g., func1(a,b) and func2(c,d). But, func2.R is being called to compute something inside func1.R as follows:

func1<-function(a,b){
 compute c and d here somehow
 e <- func2(c,d)
 return e
}

For calling a single R script like func3.R with no nested call:

func3<-function(a,b){     
  e <- a + b
  return e
}

the following Python works:

import rpy2.robjects as robjects    
def func3(a,b):
    path = 'path_to/R_files/'
    ro=robjects.r        
    ro.source(path+"func3.R")    
    return ro.func3(robjects.FloatVector(a),robjects.FloatVector(b))

What would be the Python code to use func1.R and func2.R?


Solution

  • Your func1.R script:

    #define function1 here:
    func1 <- function(c, d){
     }
    

    Your func2.R script:

    #define function 2 that uses function1
    
    source("func1.R")
    func2 <- function(a,b){
     compute c and d here somehow
     e <- func2(c,d)
     return e
    }
    

    Your python code:

    import rpy2.robjects as robjects    
    def func3(a , b):
        path = 'path_to/R_files/'
        ro = robjects.r        
        ro.source(path + "func2.R")    
        return ro.func3(robjects.FloatVector(a),robjects.FloatVector(b))