我有一个 R 脚本,其中包含一个函数,例如 myfunction。我想在 Python 中运行这个 Rscript。我的 Rscript 取决于两个参数,例如 A 和 B。我该如何管理这个?这是我的 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)
}
我在 Python 中尝试了以下操作,但没有得到任何输出。如果我在 R 中运行 R 函数,就没有问题。
A='/home/Documents/projects/'
B='somefile.txt'
import subprocess
subprocess.call(['Rscript', '/home/ali/Documents/projects/current/strain/Ali/RinPython.R', A, B])
您可以使用
rpy
从 R 中调用函数:
代码存储在两个文件中:
# 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)
}
第二个:
# 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