• 将 Python 与 RStudio IDE 配合使用(R与Python系列第一篇)


    目录

    前言:

    1-安装reticulate包

    2-安装Python,

    2.1-Step1:安装miniconda()

     2.2-Step2:安装python

    3-选择Python的默认版本(这步可以忽略)

    4-使用Python

    4.1 运行一个简单的Python脚本

    4.2 在RStudio上安装Python模块

    4.3 在 R 中调用 Python 模块

    4.4 在RStudio上调用Python脚本写的函数

    4.5 Python 与 R 对象相互转换的方式

    R → Python

    Python → R

    5-在 R Console 中交互式运行 R

    6-在RStudio中安装Python包遇到问题时解决方案

    参考:


    前言:

    RStudio 1.4为RStudio IDE带来了对Python编程语言的改进支持。本文将探讨如何将Python与R和RStudio一起使用。

    RStudio使用 R包reticulate 与Python交互,因此RStudio的Python集成需要:

    1. 安装 Python (2.7 or newer; 3.5 or newer preferred), and
    2. 安装R包reticulate (1.20 or newer, as available from CRAN)

    1-安装reticulate包

    1. install.packages("reticulate")
    2. library(reticulate)

    2-安装Python,

    2.1-Step1:安装miniconda()

    首先,需要在您的机器上安装Python。如果您还没有安装Python,可以通过几种方式安装它:

    1. (推荐)使用reticulate::install_miniconda(),使用reticulate包安装Python的Miniconda发行版;
    2. (Windows)通过https://www.python.org/downloads/windows/提供的官方Python二进制文件安装Python;
    3. (macOS)通过https://www.python.org/downloads/mac-osx/提供的官方Python二进制文件安装Python;
    4. (Linux)从源代码安装Python,或者通过操作系统的包管理器提供的Python版本安装Python。有关详细信息,请参阅https://docs.python.org/3/using/unix.html。如果您自己从源代码安装Python,最好将其安装到 /opt/python/之类的位置,这样RStudio和reticullate可以更容易地发现它。

     本文使用最简单的安装Python模式,即全程只需要在RStudio中键入多行R语言命令。

    reticulate::miniconda() #安装miniconda
    

     2.2-Step2:安装python

    reticulate::reply_python()  #安装Python

     其实,在第4节中使用Python,在R中打开一个Python脚本,运行一下,这个过程会自动运行reticulate::reply_python()函数的,可以先不执行这步,直接运行4.1节中给出的Python代码试一下,看下效果。

    其他一些有用但不必须的代码

    1. Sys.which("python") #有时不知道自己的Python在哪里,可以通过这个函数获得路径
    2. reticulate::py_available() #查看是否已经安装好Python,TRUE表示已经安装,FALSE表示没有安装。

    3-选择Python的默认版本(这步可以忽略)

     这步可以忽略,目前我在使用中,发现按照前面的步骤,到这步的时候,可以不选择Python的默认版本。不执行这一步,可以正常使用Python和安装Python模块,目前没有发现什么异常。

    (一定要配置Python环境,不然在RStudio不能成功Python包。

    可以通过Tools->Global Options…->Python配置默认版本的Python以与RStudio一起使用:)

    Python解释器也就是Python,这一步是选择Python的默认版本。

    “Python解释器(Python interpreters):”输入框显示要使用的默认Python解释器(如果有)。如果您已经知道要使用的Python解释器的位置,您可以在该输入框中键入解释器的位置。

    否则,如果输入框中没有显示默认Python解释器,可以通过单击“选择…”按钮在系统上发现Python解释器:

    RStudio将通过几种不同的方法搜索Python解释器:

    • On the PATH;
    • For virtual environments, located within the ~/.virtualenvs folder;
    • For Conda environments, as reported by conda --list,
    • For pyenv Python installations located in ~/.pyenv,
    • For Python installations located in /opt/python.

    测试环境:

    py_available() #检测Python是否安装成功,返回TRUE即表示安装成功

    4-使用Python

    4.1 运行一个简单的Python脚本

    reticulate包可以在当前运行的R会话中加载和使用Python。安装reticulate包后,可以打开Python脚本(扩展名为. py),并执行其中的代码,类似于R。

    注意到:在控制台(console)中,>表示运行R代码,>>>表示运行的Python代码。

    请注意,RStudio使用reticulate Python REPL来执行代码,并根据正在执行的脚本在R和Python之间自动切换。

    当reticulate REPL处于活动状态时,可以通过r辅助对象访问R会话中的对象。例如,r["mtcar"]可用于从R访问mtcar数据集,并将其转换为pandas DataFrame(如果可用),如果没有,则转换为Python dictionary。

    4.2 在RStudio上安装Python模块

    以pandas模块为例:

    reticulate::py_install("pandas")
    1. # 安装seaborn绘图库
    2. # pip = T指定从pip安装,默认从conda安装
    3. py_install("seaborn", pip = T)
    4. # 查看seaborn模块是否已安装
    5. py_module_available("seaborn")
    6. > [1] TRUE

    4.3 在 R 中调用 Python 模块

     例子1:

    1. # 调用os模块的listdir()函数
    2. os <- import("os")
    3. os$listdir("./")
    4. > [1] ".Rproj.user" "convert.R" "reticulate.Rmd" "Reticulate.Rproj"
    5. > [5] "Rscript.R" "summary.html" "summary.md" "summary.nb.html"
    6. > [9] "summary.Rmd" "test_pyscript.py"

     例子2:

    1. # 调用seaborn模块的load_dataset()函数
    2. # 需要seaborn模块已安装
    3. sns <- import("seaborn")
    4. tips <- sns$load_dataset("tips")
    5. print(head(tips))
    6. > total_bill tip sex smoker day time size
    7. > 1 16.99 1.01 Female No Sun Dinner 2
    8. > 2 10.34 1.66 Male No Sun Dinner 3
    9. > 3 21.01 3.50 Male No Sun Dinner 3
    10. > 4 23.68 3.31 Male No Sun Dinner 2
    11. > 5 24.59 3.61 Female No Sun Dinner 4
    12. > 6 25.29 4.71 Male No Sun Dinner 4

    4.4 在RStudio上调用Python脚本写的函数

    想法与在RStudio中调用C++自定义函数一样。建议编写的Python自定义函数名与Python脚本名称一样,这样通过source_python()函数调用这个Python自定义函数,这意味着Python自定义函数可以在RStudio中不变函数名使用,使用的其实时同名的R函数。

    例子1:

    (1)在Python环境下,编写一个Python脚本,保存为flights.py。可以看到这个python函数名为read_flights().

    1. import pandas
    2. def read_flights(file):
    3. flights = pandas.read_csv(file)
    4. flights = flights[flights['dest'] == "ORD"]
    5. flights = flights[['carrier', 'dep_delay', 'arr_delay']]
    6. flights = flights.dropna()
    7. return flights

    (2)在RStudio中使用source_python调用实现写好的flight.py文件。

    1. source_python("flights.py")
    2. flights <- read_flights("flights.csv") #使用flights.py脚本中的Python自定义函数
    3. library(ggplot2)
    4. ggplot(flights, aes(carrier, arr_delay)) + geom_point() + geom_jitter()

     例子2:

    假设 Python 脚本为test_pyscript.py,内容如下:

    1. # 打印一些数据
    2. for i in range(10):
    3. print("hello world)
    4. # 定义1个函数
    5. def sum_two_value(a, b):
    6. return a + b

    在 R 中执行 test_pyscript.py 

    1. source_python("./test_pyscript.py")
    2. > hello world
    3. > hello world
    4. > hello world
    5. > hello world
    6. > hello world
    7. > hello world
    8. > hello world
    9. > hello world
    10. > hello world
    11. > hello world
    12. sum_two_value(1, 2)
    13. > [1] 3

    4.5 Python 与 R 对象相互转换的方式

    R → Python

    设置一些R对象:

    1. A <- 1
    2. B <- c(1, 2, 3)
    3. C <- c(a = 1, b = 2, c = 3)
    4. D <- matrix(1:4, nrow = 2)
    5. E <- data.frame(a = c(1, 2), b = c(3, 4))
    6. G <- list(1, 2, 3)
    7. H <- list(c(1, 2), c(3, 4))
    8. I <- list(a = c(1, 2), b = c(3, 4))
    9. J <- function(a, b) {
    10. return(a + b)
    11. }
    12. K1 <- NULL
    13. K2 <- T
    14. K3 <- F

    上述 R 对象转为 Python 对象(Python Cell)

    1. r.A
    2. > 1.0
    3. type(r.A)
    4. > <class 'float'>
    5. r.B
    6. > [1.0, 2.0, 3.0]
    7. type(r.B)
    8. > <class 'list'>
    9. r.C
    10. > [1.0, 2.0, 3.0]
    11. type(r.C)
    12. > <class 'list'>
    13. r.D
    14. > array([[1, 3],
    15. > [2, 4]])
    16. type(r.D)
    17. > <class 'numpy.ndarray'>
    18. r.E
    19. > a b
    20. > 0 1.0 3.0
    21. > 1 2.0 4.0
    22. type(r.E)
    23. > <class 'pandas.core.frame.DataFrame'>
    24. r.G
    25. > [1.0, 2.0, 3.0]
    26. type(r.G)
    27. > <class 'list'>
    28. r.H
    29. > [[1.0, 2.0], [3.0, 4.0]]
    30. type(r.H)
    31. > <class 'list'>
    32. r.I
    33. > {'a': [1.0, 2.0], 'b': [3.0, 4.0]}
    34. type(r.I)
    35. > <class 'dict'>
    36. r.J
    37. > <function make_python_function.<locals>.python_function at 0x000001AE204ECE18>
    38. type(r.J)
    39. > <class 'function'>
    40. r.J(2, 3)
    41. > 5
    42. r.K1
    43. type(r.K1)
    44. > <class 'NoneType'>
    45. r.K2
    46. > True
    47. type(r.K2)
    48. > <class 'bool'>
    49. r.K3
    50. > False
    51. type(r.K3)
    52. > <class 'bool'>
    Python → R

    设置一些 Python 对象(Python Cell)

    1. A = 1
    2. B = [1, 2, 3]
    3. C = [[1, 2], [3, 4]]
    4. D1 = [[1], 2, 3]
    5. D2 = [[1, 2], 2, 3]
    6. E = (1, 2, 3)
    7. FF = ((1, 2), (3, 4))
    8. G = ((1, 2), 3, 4)
    9. H = {"a": [1, 2, 3],
    10. "b": [2, 3, 4]
    11. }
    12. I = {"a": 1,
    13. "b": [2, 3, 4]
    14. }
    15. def J(a, b):
    16. return a + b

     上述 Python 对象转为 R 对象(R Cell)

    1. py$A
    2. > [1] 1
    3. class(py$A)
    4. > [1] "integer"
    5. py$B
    6. > [1] 1 2 3
    7. class(py$B)
    8. > [1] "integer"
    9. py$C
    10. > [[1]]
    11. > [1] 1 2
    12. >
    13. > [[2]]
    14. > [1] 3 4
    15. class(py$C)
    16. > [1] "list"
    17. py$D1
    18. > [[1]]
    19. > [1] 1
    20. >
    21. > [[2]]
    22. > [1] 2
    23. >
    24. > [[3]]
    25. > [1] 3
    26. class(py$D1)
    27. > [1] "list"
    28. py$D2
    29. > [[1]]
    30. > [1] 1 2
    31. >
    32. > [[2]]
    33. > [1] 2
    34. >
    35. > [[3]]
    36. > [1] 3
    37. class(py$D2)
    38. > [1] "list"
    39. py$E
    40. > [[1]]
    41. > [1] 1
    42. >
    43. > [[2]]
    44. > [1] 2
    45. >
    46. > [[3]]
    47. > [1] 3
    48. class(py$E)
    49. > [1] "list"
    50. py$FF
    51. > [[1]]
    52. > [[1]][[1]]
    53. > [1] 1
    54. >
    55. > [[1]][[2]]
    56. > [1] 2
    57. >
    58. >
    59. > [[2]]
    60. > [[2]][[1]]
    61. > [1] 3
    62. >
    63. > [[2]][[2]]
    64. > [1] 4
    65. class(py$FF)
    66. > [1] "list"
    67. py$G
    68. > [[1]]
    69. > [[1]][[1]]
    70. > [1] 1
    71. >
    72. > [[1]][[2]]
    73. > [1] 2
    74. >
    75. >
    76. > [[2]]
    77. > [1] 3
    78. >
    79. > [[3]]
    80. > [1] 4
    81. class(py$G)
    82. > [1] "list"
    83. py$H
    84. > $a
    85. > [1] 1 2 3
    86. >
    87. > $b
    88. > [1] 2 3 4
    89. class(py$H)
    90. > [1] "list"
    91. py$I
    92. > $a
    93. > [1] 1
    94. >
    95. > $b
    96. > [1] 2 3 4
    97. class(py$I)
    98. > [1] "list"
    99. py$J
    100. > <function J at 0x000001AE204ECE18>
    101. class(py$J)
    102. > [1] "python.builtin.function" "python.builtin.object"
    103. py$J(2, 3)
    104. > [1] 5

    5-在 R Console 中交互式运行 R

    • repl_python () 进入 Python 环境
    • exit 退出 Python 环境

    6-在RStudio中安装Python包遇到问题时解决方案

    问题:No module named 'tensorflow_probability' 

    通过在新的R会话中运行以下操作可以解决许多安装问题(您可以使用Ctrl+Shift+F10在Rdios中重新启动R):

    # install the development version of packages, in case the
    # issue is already fixed but not on CRAN yet.
    install.packages("remotes")
    remotes::install_github(sprintf("rstudio/%s", c("reticulate", "tensorflow", "keras")))
    reticulate::miniconda_uninstall() # start with a blank slate
    reticulate::install_miniconda()
    tfprobability::install_tfprobability()

     注意:其中在miniconda_uninstall() 卸载之前安装的miniconda时,要将RStudio中Tools-->Global Options--->Python-->将Python interpreter(Python解释器)清除掉。(注:下图是已经清除掉的界面,如果没有执行清楚操作,Python interpreter输入框中是有内容的)。

    参考:

    https://support.posit.co/hc/en-us/articles/1500007929061 (给出了在RStudio中配置Python环境的最简单方法)

    🤔 Reticulate | 如何在Rstudio中优雅地调用Python!? - 知乎 (zhihu.com) (给出了安装Python包的命令)

    No module named 'tensorflow_probability' · Issue #155 · rstudio/tfprobability · GitHub (安装包遇到问题时的解决办法)

    reticulate:在R中使用Python - 知乎 (zhihu.com)

  • 相关阅读:
    pip修改为镜像源,window和linux修改方式
    第26章_瑞萨MCU零基础入门系列教程之独立看门狗定时器-IWDT
    TIA博途Wincc Advanced下载项目的具体方法演示(V16版本)
    Array和ArrayList有什么区别呢?
    安卓Webview中异步加载资源
    吃货告诉你,PAAS、IAAS和SAAS之间的区别
    RedisSearch深度解析:探索全文搜索的新境界
    基于深度神经网络的中药材识别
    封装自己的jq myFullPage插件
    【Python】初学者喜欢的Python入门笔记
  • 原文地址:https://blog.csdn.net/u011375991/article/details/132620433