• python3调用R语言干货


    R语言知识:https://www.w3cschool.cn/r/r_lists.html

    1. 安装库rpy2

    1. 下载与本地对应python版本模块,pip install rpy2是安装不上的

    下载地址是:http://www.lfd.uci.edu/~gohlke/pythonlibs/#rpy2  这是python下包的专用地址
    需要下载版本和平台都相对应的whl包,我下的是rpy2-2.9.4-cp36-cp36m-win32.whl

    pip install rpy2-2.9.4-cp36-cp36m-win32.whl安装即可。

     如果还不行,参考:https://www.cnblogs.com/caiyishuai/p/9520214.html

    2. 安装broom --》R语言的一个库--》与R脚本有关,可以忽略

    install.packages('broom')

    3. 写R脚本

    library(broom)
    
    test <- function() {
      # x <- c(1:1200000)
      # y <- c(1:1200000)
      x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
      y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
      
      relation <- lm(y ~ x)
      data <- summary(relation)
      
      data_dict <- c()
      
      newData <- c(data)
      data_dict["residuals"] <- newData["residuals"]
      data_dict["coefficients"] = newData["coefficients"]
      data_dict["aliased"] = newData["aliased"]
      data_dict["sigma"] = newData["sigma"]
      data_dict["df"] = newData["df"]
      data_dict["r.squared"] = newData["r.squared"]
      data_dict["adj.r.squared"] = newData["adj.r.squared"]
      data_dict["fstatistic"] = newData["fstatistic"]
      data_dict["cov.unscaled"] = newData["cov.unscaled"]
      data_dict["p.value"] = c(broom::glance(data))["p.value"]
      
      return(data_dict)
    }
    
    
    # result <- test()
    # print(result)

    4. 写python脚本

    报错: RuntimeError: R_USER not defined.

    解决方案,各种搜索都是环境变量的问题,于是我各种加

     还tm不行..........................................又懒得重启

    stackflow找到答案

    os模块的运用,直接看脚本

    import os
    os.environ['R_HOME'] = r'C:Program FilesRR-3.6.0'
    os.environ['R_USER'] = r'C:python3.6.3Libsite-packages
    py2' #path depe
    
    import rpy2.robjects as robjects   # ----------------------------------------------> 一定要注意这句,不能放到最上面,因为要先添加环境变量,才能找到这个rpy2。一定要注意
    robjects.r.source(r'C:code
    _test	est_one	est.R')
    a = robjects.r('test()')
    print(type(a))
    # print(list(a))
    from pandas import DataFrame
    print(a[0])
    print(a[0][0])

    打印结果,以及转换数据类型,参考:http://rpy.sourceforge.net/rpy2/doc-2.2/html/vector.html#creating-vectors                  https://blog.csdn.net/suzyu12345/article/details/50587267

    5. python传值给R脚本,如何实现, 形参方法1

    R脚本: 这个脚本的关键在于如何将list转换为c

    library(broom)
    
    test <- function(list_data) {
      # print(list_data)
      # print(class(list_data))
      # r语言list 转换成 vector: v = as.vector(unlist(你的list))
      x = c(as.vector(unlist(list_data['x'])))
      y = c(as.vector(unlist(list_data['y'])))
    
      
      relation <- lm(y ~ x)
      data <- summary(relation)
      print(data)
    
      return(0)
    }

    python脚本

    import os
    
    os.environ['R_HOME'] = r'C:Program FilesRR-3.6.0'
    os.environ['R_USER'] = r'C:python3.6.3Libsite-packages
    py2' #path depe
    
    from pandas import DataFrame as df
    import rpy2.robjects as robjects
    import time
    robjects.r.source(r'C:code
    _test	est_one	est.R')
    
    time1 = time.time()
    
    y =  robjects.ListVector({
        "x":[1, 2, 3],
        "y":[1, 2, 3], # 这里可以给float
    
        })
    a = robjects.r["test"](y)
    

    6. python传值给R脚本,如何实现, 形参方法2:类似python的args

    R语言脚本

    library(broom)
    
    test <- function(...) {
      list_data <- list(...) # 类似python的args,可以传递多个参数
      print(list_data)
      print(class(list_data))
      x = c(as.vector(unlist(list_data[1]))) # 注意R是从1开始的
      y = c(as.vector(unlist(list_data[2])))
      print(x)
      print(y)
    
    
      
      relation <- lm(y ~ x)
      data <- summary(relation)
      print(data)
    
      return(0)
    }

    python语言

    import os
    
    os.environ['R_HOME'] = r'C:Program FilesRR-3.6.0'
    os.environ['R_USER'] = r'C:python3.6.3Libsite-packages
    py2' #path depe
    
    from pandas import DataFrame as df
    import rpy2.robjects as robjects
    import time
    robjects.r.source(r'C:code
    _test	est_one	est.R')
    
    x =  robjects.IntVector([151, 174, 138, 186, 128, 136, 179, 163, 152, 131])
    y =  robjects.IntVector([63, 81, 56, 91, 47, 57, 76, 72, 62, 48])
    
    a = robjects.r["test"](x, y)
    
    

     

  • 相关阅读:
    Spring杂谈 | 什么是ObjectFactory?什么是ObjectProvider?
    一次相亲经历,我彻底搞懂了什么叫阻塞非阻塞,同步异步
    Spring杂谈 | 你真的了解泛型吗?从java的Type到Spring的ResolvableType
    Spring官网阅读(十二)ApplicationContext详解(中)
    Spring官网阅读(十一)ApplicationContext详细介绍(上)
    Spring官网阅读(十)Spring中Bean的生命周期(下)
    Spring官网阅读(九)Spring中Bean的生命周期(上)
    influxDB 0.9 C# 读写类
    使用HAProxy实现sql server读库的负载均衡
    influxdb基本操作
  • 原文地址:https://www.cnblogs.com/renfanzi/p/11122305.html
Copyright © 2020-2023  润新知