Python调用R代码

import pandas as pd
import rpy2.robjects as robjects
#pandas和r中的dataframe类型转换需要用到pandas2ri  
from rpy2.robjects import pandas2ri   

pandas2ri.activate()
robjects.r(''''' 
     library(dplyr)  # 导入包测试
     ''')  

caculate = robjects.r(''''' 
       f <- function(dat, fun){
              x = dat[,1]
              y = dat[,2]
              if(fun=='add'){
                result = x+y
              }
              if (fun=='division'){
                result = x/y
              }
              return(result)
       } 
       ''')   # 自定义函数
#通过pandas2ri.py2ri将pandas的dataframe转成r作为输入,再使用pandas2ri.ri2py将输出的r中的dataframe转成pandas          
dat = pd.DataFrame({'x':[1,2,3], 'y':[2,2,2]})
result = pandas2ri.ri2py((caculate(pandas2ri.py2ri(dat), "add")))  # [3, 4, 5]
result = pandas2ri.ri2py((caculate(pandas2ri.py2ri(dat), "division")))  # [0.5, 1. , 1.5]

你可能感兴趣的:(Python调用R代码)