#!/usr/bin/env python # coding: utf-8 # ### 计算新闻传播学课程 # # *** # *** # # # rpy2: Using R within Jupyter Notebook # # *** # *** # # 王成军 # # wangchengjun@nju.edu.cn # # 计算传播网 http://computational-communication.com # > conda install rpy2 # In[1]: get_ipython().run_line_magic('load_ext', 'rpy2.ipython') # conda install rpy2 # # Rpush: push Python object to R # In[57]: import numpy as np X = np.array([4.5,6.3,7.9, 10.3]) get_ipython().run_line_magic('Rpush', 'X') get_ipython().run_line_magic('R', 'mean(X)') # In[58]: get_ipython().run_cell_magic('R', '', 'Y = c(2,4,3,9)\nsummary(lm(Y~X))\n') # In[59]: get_ipython().run_line_magic('R', 'plot(X, Y)') # In[60]: get_ipython().run_line_magic('R', 'dat = data.frame(X, Y)') # # Rpull: pull data from R to python # # https://rpy2.github.io/doc/latest/html/interactive.html?highlight=rpull#rpy2.ipython.rmagic.RMagics.Rpull # # Not work for Python 3.X # In[90]: get_ipython().run_line_magic('R', "x = c(3,4,6.7); y = c(4,6,7); z = c('a',3,4)") # In[91]: get_ipython().run_line_magic('R', 'x') # In[95]: x # In[66]: get_ipython().run_line_magic('Rpull', 'dat') # In[67]: dat # In[17]: # import rpy2's package module import rpy2.robjects.packages as rpackages # import R's utility package utils = rpackages.importr('utils') # In[77]: # select a mirror for R packages utils.chooseCRANmirror() # In[78]: # R package names packnames = ('ggplot2', 'hexbin') # R vector of strings from rpy2.robjects.vectors import StrVector # Selectively install what needs to be install. # We are fancy, just because we can. names_to_install = packnames if len(names_to_install) > 0: utils.install_packages(StrVector(names_to_install)) # In[2]: import rpy2.interactive as r import rpy2.interactive.packages # this can take few seconds r.packages.importr('ggplot2') # In[80]: get_ipython().run_cell_magic('R', '', 'p = ggplot(data = dat, mapping = aes(x = X, y =Y))\np + geom_point()\n') # In[81]: get_ipython().run_cell_magic('R', '', 'library(lattice)\nattach(mtcars)\n\n# scatterplot matrix\nsplom(mtcars[c(1,3,4,5,6)], main="MTCARS Data")\n') # In[82]: get_ipython().run_cell_magic('R', '', 'data(diamonds) \nset.seed(42) \nsmall = diamonds[sample(nrow(diamonds), 1000), ] \nhead(small)\n\np = ggplot(data = small, mapping = aes(x = carat, y = price))\np + geom_point()\n') # In[83]: get_ipython().run_cell_magic('R', '', 'p = ggplot(data=small, mapping=aes(x=carat, y=price, shape=cut, colour=color)) \np+geom_point()\n') # In[84]: import rpy2.robjects as ro from rpy2.robjects.packages import importr base = importr('base') fit_full = ro.r("lm('mpg ~ wt + cyl', data=mtcars)") print(base.summary(fit_full)) # In[85]: diamonds = ro.r("data(diamonds)") # In[86]: get_ipython().run_line_magic('R', 'head(diamonds)') # In[87]: fit_dia = ro.r("lm('price ~ carat + cut + color + clarity + depth', data=diamonds)") # In[88]: print(base.summary(fit_dia)) # # END # In[ ]: