# 1. 调用自定义函数 robjects.r(''' f <- function(r){pi * r} ''') t3=robjects.r['f'](3) # 3 为传递的参数 print('%.3f'%t3[0]) # 复杂的例子 r_script = ''' library(randomForest) # 导入随机森林包 ## use data set iris data = iris # 使用鸢尾花数据集 table(data$Species) ## create a randomForest model to classfy the iris species # 创建随机森林模型给鸢尾花分类 iris.rf <- randomForest(Species~., data = data, importance=T, proximity=T) print('--------here is the random model-------') print(iris.rf) print('--------here is the names of model-----') print(names(iris.rf)) confusion = iris.rf$confusion print(confusion) ''' robjects.r(r_script) # 2. 调用R自带的函数 # internal function in R t4=robjects.r['ls']()#可使用 ls()函数列出工作区中的所有变量;ls() 函数可以使用模式来匹配变量名称,eg:ls(pattern="var"),列出以“var”模式开头的变量 print(t4[0]) # another internal function l = robjects.r['letters'] print(l) print(len(l)) print(robjects.r['paste'](l, collapse = '-')) output: [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" [20] "t" "u" "v" "w" "x" "y" "z" 26 [1] "a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z" # an alternative way of getting 'paste' function in R # eval the R code coder = 'paste(%s, collapse = "-")' % (l.r_repr()) print(robjects.r(coder)) [1] "a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z" # 3. 执行R的脚本文件 robjects.r.source('/home/rongzhengqin2/learn/rpy2/test01.r') x = robjects.r('x')#获取脚本里的变量 y = robjects.r('y') print(x) #[1] 1 2 3 4 print(y) #[1] 1 4 9 16 # 4. 载入和使用R包 from rpy2.robjects.packages import importr stats = importr('stats') print('stats.rnorm(10):',stats.rnorm(10)) output: stats.rnorm(10): [1] -0.02499746 1.92827632 0.93832232 0.62033276 2.15107656 -0.26479198 [7] 0.59109714 -0.34845466 0.32339794 -1.78048630