Search code examples
pythonrsubprocess

Calling R functions in Python with parameters


I have an R script which contains a function, say myfunction. I'd like to run this Rscript in Python. My Rscript depends on two parameters, say A and B. How can I manage this? Here is my R script.

myfunction= function(A,B){
  A=read.table(paste0(A,B))
  A=A[,1:3]
  A=data.frame(A)
  colnames(A)[1:3]=c('POS','REF','ALT')
  estimates=strain_p_estimates_likelihood(Data=A,n_iterations=10)
  write.csv(estimates,paste0(A,'estimates.csv'), row.names = FALSE)
}

I tried the following in Python but I am not getting any output. If I run the R function in R, I have no issues.

A='/home/Documents/projects/'
B='somefile.txt'

import subprocess
subprocess.call(['Rscript', '/home/ali/Documents/projects/current/strain/Ali/RinPython.R', A, B])

Solution

  • You can use rpy to call functions from R:

    Code is stored in the two files:

    # code.R
    
    myfunction= function(A,B){
      A=read.table(paste0(A,B))
      A=A[,1:3]
      A=data.frame(A)
      colnames(A)[1:3]=c('POS','REF','ALT')
      estimates=strain_p_estimates_likelihood(Data=A,n_iterations=10)
      write.csv(estimates,paste0(A,'estimates.csv'), row.names = FALSE)
    }
    

    and the second one:

    # script.py
    import rpy2.robjects as robjects
    from rpy2.robjects import pandas2ri
    
    
    A='/home/Documents/projects/'
    B='somefile.txt'
    
    r = robjects.r
    r['source']('code.R') # preload code from the R file
    
    # Loading the function we have defined in R.
    myfunction_r = robjects.globalenv['myfunction']
    myfunction_r(A, B) # this will call your R funciton