jupyterLab+R,让你更优雅的探索数据

jupyterLab+R,让你更优雅的探索数据

作者厚缊R语言中文社区专栏作者。

公众号:统计与编程语言


jupyterLab 是神马东西?

现在Rstudio已经成为R社区使用最广泛的集成编辑器,其在配合Rstudio公司开发的软件包使用上有天然的优势,如knitrbookdownblogdownsparklyrtidyverse等,让我们在数据导入、清洗、可视化、分析过程中少踩了不少坑。

然而,有时候我们也会发现,利用Rmarkdown进行探索性数据分析时,尤其是初学者,总是不断花费时间在文档编译上,而压缩了真正数据探索的时间。很多时候,我很羡慕python用户,因为他们拥有Ipython、jupyter notebook等工具,让我们一边分析数据,一边插入markdown文本,并且还能实时看到结果,这些特性R用户也可以实现吗?当然,这就是我今天推荐的jupyterlab 编辑器。

安装jupyterLab

首先我们要明白,jupyterLab是一个python包,所以要使用jupyterLab首先要配置python环境。对于普通用户,包括linux、win和Mac用户,建议直接下载anaconda发行版进行安装,这样免去了既要安装python又要安装其他包的麻烦,是最简洁的方法。

对于平时很少使用python的人来说,可能无法忍受anaconda全家桶式的安装模式,想更轻便的安装使用,那也很容易。


1. 安装

Mac 和 Linux用户系统自带了python,可以直接使用pip install jupyterlab安装jupyterLab包。

win用户先在python官网下载安装python,然后使用pip install jupyterlab安装jupyterLab包。


2. 运行

在终端输入jupyter lab即可以在默认浏览器中打开编辑器界面,若不能,请检查下python路径配置是否正确。

“咦,怎么只能选择python,R去哪了”,各位看官莫急,这是因为R端缺少必要的包,还不能和jupyter进行通信,等把这些包安装好进行配置后就可以了。


3. 配置R

⚠️ 要把先前打开的jupyterLab程序全部关闭后再进行以下操作


#安装必要的依赖包

install.packages(c('repr''IRdisplay'
                  'evaluate''crayon'
                  'pbdZMQ''devtools'
                   'uuid''digest')) 
                   
#IRkernel包没有放在CRAN上,需要通过GitHub安装
devtools::install_github('IRkernel/IRkernel'
IRkernel::installspec() #确保jupyterLab能找到R解释器安装位置


4. 再次在终端运行`jupyter lab`,选择R图标打开,你就可以在jupyterLab进行数据分析啦

jupyterLab的主要特性

绘图函数自动插入图片

ggplot2绘图完美支持


options(repr.plot.width=7, repr.plot.height=5)
library(WDI) 
library(ggplot2)

# 获取数据

dat <- WDI(indicator='NY.GNP.PCAP.CD'
          country=c('CL','HU','UY'), start=1960, end=2012
p <- ggplot(dat, aes(year, NY.GNP.PCAP.CD, color=country)) + 
           geom_line() +
            xlab('Year') + 
            ylab('GDI per capita (Atlas Method USD)') +
            labs(title <- "GNI Per Capita ($USD Atlas Method)")
p

jupyterLab+R,让你更优雅的探索数据


动态绘图没问题


library(plotly)
ggplotly(p)

jupyterLab+R,让你更优雅的探索数据


网页也可以

也可以直接插入plotly包官网示例,这里需要用到IRdisplay包提供的函数。其核心思想是使用display_html()函数将示例网页封装为iframe进行输出。

这一方法可以用来插入任何网页,包含视频、音频等等。当然,相应地高度、宽度需要进行针对性调整。


library(IRdisplay)
plotly_iframe <- function(url) {
    # set width and height from options or default square
    w <- "750"
    h <- "600"
    html <- paste("<center><iframe height="", h, 
                  "" id="igraph" scrolling="no" 
                 seamless="seamless"src=""
,
                   url, "" width="", w, 
                   "" frameBorder="0"></iframe></center>"
                   sep="")
    return(html)
##封装一个html中的iframe,方便display_html调用


display_html(plotly_iframe("https://plot.ly/~ggplot2examples/98"))

jupyterLab+R,让你更优雅的探索数据


leaflet地图也很容易


library(leaflet)
library(leafletCN)
m <- leaflet() %>%
  amap() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=121.48024, lat=31.23631, popup="Shanghai")
  
htmlwidgets::saveWidget(m, 'leaflet.html', selfcontained = FALSE)

display_html(paste("<center>","",'<iframe src="leaflet.html" 
width="960" height="500",align="absmiddle"></iframe>'
,"","</center>"))

jupyterLab+R,让你更优雅的探索数据

插入常见统计报表

数据框、矩阵格式化输出


data(iris)
head(iris) #数据框自动转化为表格

Sepal.Length

Sepal.Width

Petal.Length

Petal.Width

Species






5.1 

3.5 

1.4 

0.2 

setosa

4.9 

3.0 

1.4 

0.2 

setosa

4.7 

3.2 

1.3 

0.2 

setosa

4.6 

3.1 

1.5 

0.2 

setosa

5.0 

3.6 

1.4 

0.2 

setosa

5.4 

3.9 

1.7 

0.4 

setosa


matrix(1:15,nrow=3#矩阵默认不显示索引

10

13

11

14

12

15

更复杂的表格输出


m <- DT::datatable(iris[1:20, c(5,1:4)],  rownames = FALSE)
htmlwidgets::saveWidget(m, 'demo.html', selfcontained = FALSE)
display_html(
paste("<center>","",
      '<iframe src="demo.html" width="1050" height="600">
      </iframe>'
,
     "","</center>"))

jupyterLab+R,让你更优雅的探索数据

统计报表输出


library(stargazer)
library(IRdisplay)
library(magrittr)
m <- capture.output(stargazer(attitude,type='html')) 
#stargazer()函数会自动输出,用capture.output()捕捉这些输出文本
display_html(paste("<center>","",m,"","</center>"))

jupyterLab+R,让你更优雅的探索数据


linear.1 <- lm(rating ~ complaints + privileges + learning + raises + critical,
               data=attitude)
linear.2 <- lm(rating ~ complaints + privileges + learning, data=attitude)
attitude$high.rating <- (attitude$rating > 70)
probit.model <- glm(high.rating ~ learning + critical + advance, data=attitude,
                    family = binomial(link = "probit"))
outreg <- capture.output(

     stargazer(linear.1, linear.2, probit.model, 
               title="Regression Results", align=TRUE
               dep.var.labels=c("Overall Rating","High Rating"), 
               covariate.labels=c("Handling of Complaints",
                                  "No Special Privileges"
                                  "Opportunity to Learn",
                                  "Performance-Based Raises",
                                  "Too Critical","Advancement"), 
               omit.stat=c("LL","ser","f"), 
               no.space=TRUE,type='html')
)
display_html(paste("<center>","",outreg,"","</center>")) #为了美观,手动添加了html 居中标签

Regression Results

jupyterLab+R,让你更优雅的探索数据

latex数学公式支持

添加公式的方法

jupyterLab 数学公式本质上是调用的MathJax宏包进行处理的,因此要使用数学公式需要把单元格设置为markdown模式。可以通过下拉菜单进行手动设置,也可以选中单元格,按esc退出编辑模式,然后按m进行设置。


1. 行内公式

行内公式样式为$行内公式$,公式内容通过两个美元符号包裹起来。例如,这里是行内公式$sum_{k=1}^inftyrac{x^n}{n!}$,编译后显示为∑k=1∞xnn!k=1n!xn


2. 行间公式

行间公式样式为$$行间公式$$,公式内容前后各两个美元符号。例如,这里是行间公式$$x^n+y^n=z^n$$,编译后显示为:

jupyterLab+R,让你更优雅的探索数据


更复杂的数学公式解决办法

很多时候需要写条件函数,需要使用cases环境。


$$
f(n) =
egin{cases}
n/2,  & ext{if $n$ is even} 
3n+1, & ext{if $n$ is odd}
end{cases}
$$

jupyterLab+R,让你更优雅的探索数据


公式组使用array环境。




left{ 
egin{array}{c}
    a_1x+b_1y+c_1z=d_1  
    a_2x+b_2y+c_2z=d_2  
    a_3x+b_3y+c_3z=d_3
end{array}
ight.

jupyterLab+R,让你更优雅的探索数据

矩阵代数直接使用matrix环境。


X=left(
    egin{matrix}
        x_{11} & x_{12} & cdots & x_{1d}
        x_{21} & x_{22} & cdots & x_{2d}
        dots & dots & ddots & dots
        x_{m1} & x_{m2} & cdots & x_{md}
    end{matrix}
ight)
=left(
     egin{matrix}
            x_1^T 
            x_2^T 
            dots
            x_m^T 
        end{matrix}
ight)

jupyterLab+R,让你更优雅的探索数据


对齐使用align环境。



egin{align}
rac{partial J(heta)}{partialheta_j}
& = -rac1msum_{i=0}^m(y^i-h_heta(x^i)) rac{partial}{partialheta_j}(y^i-h_heta(x^i)) 
& = -rac1msum_{i=0}^m(y^i-h_heta(x^i)) rac{partial}{partialheta_j}(sum_{j=0}^nheta_jx_j^i-y^i) 
& = -rac1msum_{i=0}^m(y^i-h_heta(x^i))x^i_j
end{align}

jupyterLab+R,让你更优雅的探索数据

最后还说下公式自动编号。我在测试时直接使用equation环境并没有得到编号的公式。具体原因我还不清楚。


egin{equation}
a+b = 1 
c+d = 2
end{equation}

jupyterLab+R,让你更优雅的探索数据


快捷键

要熟悉jupyter快捷键,必须要要清楚jupyter单元格(cell)分编辑模式和非编辑模式,快捷键都是在非编辑模式下才能起作用。

Shift + Enter:运行本单元,选中下个单元

Ctrl + Enter:运行本单元

Esc:切换单元格为非编辑模式

Enter:切换单元格为编辑模式

dd:删除选中单元格

A:在上方插入单元格

B:在下方插入单元格

M:切换单元格为markdown模式

R:切换单元格为raw模式

Y:切换单元格为code模式

jupyter 提供了大量的快捷键方便使用,平时我用的最多的就上面一些,其他的可以参照lawme的专栏文章。

写在最后的话

jupyterLab比较适合进行探索性数据分析和学习,在使用过程中最大的缺点是当文档过大,或者涉及很多动态页面生成时容易卡顿。与之相对的,使用Rstudio结合Rmarkdown生成最终报告文档可能更合适,两者各有优缺点,需要结合使用。

PS:第一次写,有什么疏忽各位砖轻点拍jupyterLab+R,让你更优雅的探索数据jupyterLab+R,让你更优雅的探索数据jupyterLab+R,让你更优雅的探索数据


jupyterLab+R,让你更优雅的探索数据

jupyterLab+R,让你更优雅的探索数据

公众号后台回复关键字即可学习

回复 爬虫                爬虫三大案例实战  
回复 Python           
1小时破冰入门

回复 数据挖掘         R语言入门及数据挖掘
回复 人工智能         三个月入门人工智能
回复 数据分析师      数据分析师成长之路 
回复 机器学习          机器学习的商业应用
回复 数据科学          数据科学实战
回复 常用算法          常用数据挖掘算法