学习小组54期 6th day-R package--忍冬

2020-04-22

今日内容:

学习R包
“R包使用是一通百通”--突然之间有了信心

以dplyr为例,讲一下R包

  1. 安装和加载R包
    1.1 镜像设置

你还在每次配置Rstudio的下载镜像吗?

 1.1.1 之前按教程设置过清华cran镜像的局限性

cran清华大学的镜像设置

但是:如果要下载Bioconductor的包,这个镜像是没有办法用的;另外即使设置了这里,Rstudio也不是每次都能真的从CRAN去下载包,可以通过options()$repos来检验,很多时候还是无奈地回到了R的国外官网

#`options`函数就是设置R运行过程中的一些选项设置
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源
# 当然可以换成其他地区的镜像

 1.1.2 但是这种方法还可能有问题

下次再打开Rstudio会发现,下载Bioconductor还是会回到官方镜像,可以查询options()$BioC_mirror 试试,如果依然是自己设置的国内镜像,就不用管了;如果发现需要再重新运行一遍代码进行设置,那么就需要继续看下面的内容

 1.1.3 这里就需要用到R的配置文件 .Rprofile

Rstudio最重要的两个配置文件:.Renviron--它是为了设置R的环境变量(这里先不说它);而.Rprofile是一个代码文件,如果启动时找到这个文件,那么先运行一遍(这个过程就是在启动Rstudio时完成的)
这个文件的配置可以多样(比如linux中在.bashrc文件中添加alias 作为快捷命令)

首先用file.edit()来编辑文件

file.edit('~/.Rprofile')

然后在其中添加好上面的两行options代码

options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源

 1.2 安装
R包安装命令是install.packages(“包”)或者BiocManager::install(“包”)

取决于你要安装的包存在于CRAN网站还是Biocductor。具体位置需自行搜索。

 1.3 加载
library(包) require(包)
R语言中的数据处理包dplyr、tidyr笔记

已安装并加载好dplyr

 1.4 加载实例数据集以应用dplyr:

> test <- iris[c(1:2,51:52,101:102),]
> View(test)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
51 7.0 3.2 4.7 1.4 versicolor
52 6.4 3.2 4.5 1.5 versicolor
101 6.3 3.3 6.0 2.5 virginica
102 5.8 2.7 5.1 1.9 virginica

dplyr: Single table verbs
Dplyr aims to provide a function for each basic verb of data manipulation:
filter()to select cases based on their values.
arrange() to reorder the cases.
select() and rename() to select variables based on their names.
mutate() and transmute() to add new variables that are functions of existing variables.
summarise() to condense multiple values to a single value.
sample_n() and sample_frac() to take random samples.

  • mutate()增加列数
    Add new columns with mutate()
    Besides selecting sets of existing columns, it’s often useful to add new columns that are functions of existing columns. This is the job of mutate():
mutate(flights,
  gain = arr_delay - dep_delay,
  speed = distance / air_time * 60
)


> mutate(test, new = Sepal.Length * Sepal.Width) #mutate() and transmute() to add new variables that are functions of existing variables.
  Sepal.Length Sepal.Width Petal.Length Petal.Width    Species   new
1          5.1         3.5          1.4         0.2     setosa 17.85
2          4.9         3.0          1.4         0.2     setosa 14.70
3          7.0         3.2          4.7         1.4 versicolor 22.40
4          6.4         3.2          4.5         1.5 versicolor 20.48
5          6.3         3.3          6.0         2.5  virginica 20.79
6          5.8         2.7          5.1         1.9  virginica 15.66
  • select(),按列号筛选
> select(test,1)
    Sepal.Length
1            5.1
2            4.9
51           7.0
52           6.4
101          6.3
102          5.8
> select(test,c(1,5))
    Sepal.Length    Species
1            5.1     setosa
2            4.9     setosa
51           7.0 versicolor
52           6.4 versicolor
101          6.3  virginica
102          5.8  virginica
  • select(),按列名筛选
 select(test,Sepal.Width,Petal.Width)
    Sepal.Width Petal.Width
1           3.5         0.2
2           3.0         0.2
51          3.2         1.4
52          3.2         1.5
101         3.3         2.5
102         2.7         1.9
> select(test, one_of(vars))       #one_of是个特殊的函数,不能单独使用,出自tidyselect,只能和select连用。
    Petal.Width    Species
1           0.2     setosa
2           0.2     setosa
51          1.4 versicolor
52          1.5 versicolor
101         2.5  virginica
102         1.9  virginica
  • filter(),筛选行 based on their values
> filter(test,Species=="setosa")  #setosa为其值
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
> filter(test,Species=="setosa"&Sepal.Width>3.2)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa

# %in%用法    

     
a %in% table     #a值是否包含于table中,为真输出TURE,否者输出FALSE
#首先复制两个变量a和b
>a <- 1:5
>b <- 3:7
>a %in% b    #看a的元素是否包含版在b中输出结权果如下:
[1] FALSE FALSE  TRUE  TRUE  TRUE

> filter(test,Species %in% c("setosa","virginica"))    #species
  Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
1          5.1         3.5          1.4         0.2    setosa
2          4.9         3.0          1.4         0.2    setosa
3          6.3         3.3          6.0         2.5 virginica
4          5.8         2.7          5.1         1.9 virginica
> filter(test,Species==c("setosa","virginica"))
  Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
1          5.1         3.5          1.4         0.2    setosa
2          5.8         2.7          5.1         1.9 virginica
  • arrange(),按某1列或某几列对整个表格进行排序
> arrange(test,Sepal.Width) #默认从小到大排序
  Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1          5.8         2.7          5.1         1.9  virginica
2          4.9         3.0          1.4         0.2     setosa
3          7.0         3.2          4.7         1.4 versicolor
4          6.4         3.2          4.5         1.5 versicolor
5          6.3         3.3          6.0         2.5  virginica
6          5.1         3.5          1.4         0.2     setosa
> arrange(test, desc(Sepal.Width)) #用desc从大到小 
  Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1          5.1         3.5          1.4         0.2     setosa
2          6.3         3.3          6.0         2.5  virginica
3          7.0         3.2          4.7         1.4 versicolor
4          6.4         3.2          4.5         1.5 versicolor
5          4.9         3.0          1.4         0.2     setosa
6          5.8         2.7          5.1         1.9  virginica```

%in%很简单

  • summarise():汇总(value)

结合group_by使用实用性强

> summarize(test,mean(Sepal.Width),sd(Sepal.Width)) # 计算Sepal.W的平均值和标准差
  mean(Sepal.Width) sd(Sepal.Width)
1              3.15       0.2738613
# 先按照Species分组,计算每组Sepal.W的平均值和标准差
> group_by(test,Species)
# A tibble: 6 x 5
# Groups:   Species [3]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species   
*        <dbl>       <dbl>        <dbl>       <dbl> <fct>     
1          5.1         3.5          1.4         0.2 setosa    
2          4.9         3            1.4         0.2 setosa    
3          7           3.2          4.7         1.4 versicolor
4          6.4         3.2          4.5         1.5 versicolor
5          6.3         3.3          6           2.5 virginica 
6          5.8         2.7          5.1         1.9 virginica 
> summarise(group_by(test, Species),mean(Sepal.Width), sd(Sepal.Width))
# A tibble: 3 x 3
  Species    `mean(Sepal.Width)` `sd(Sepal.Width)`
  <fct>                    <dbl>             <dbl>
1 setosa                    3.25             0.354
2 versicolor                3.2              0    
3 virginica                 3                0.424
  1. dplyr两个实用技能
    2.1 管道操作 %>% (cmd/ctr + shift + M)

加载任意一个tidyverse包即可用管道符号


https://blog.csdn.net/zhaozhn5/article/details/79001384

%>% 向右操作符(forward-pipe operator)
%>%是最常用的一个操作符,就是把左侧准备的数据或表达式,传递给右侧的函数调用或表达式进行运行,可以连续操作就像一个链条一样。
现实原理如上图所示,使用%>%把左侧的程序的数据集A传递右侧程序的B函数,B函数的结果数据集再向右侧传递给C函数,最后完成数据计算。

> test %>% 
+     group_by(Species) %>% 
+     summarise(mean(Sepal.Width), sd(Sepal.Width))
# A tibble: 3 x 3
  Species    `mean(Sepal.Width)` `sd(Sepal.Width)`
  <fct>                    <dbl>             <dbl>
1 setosa                    3.25             0.354
2 versicolor                3.2              0    
3 virginica                 3                0.424

 2.2 count统计某列的unique值

 count(test,Species)
# A tibble: 3 x 2
  Species        n
  <fct>      <int>
1 setosa         2
2 versicolor     2
3 virginica      2
> count(test,Sepal.Width)
# A tibble: 5 x 2
  Sepal.Width     n
        <dbl> <int>
1         2.7     1
2         3       1
3         3.2     2
4         3.3     1
5         3.5     1
  1. dplyr处理关系数据

即:将2个表进行连接,注意:不要引入factor

> test1 <- data.frame(x = c('b','e','f','x'), 
+                     z = c("A","B","C",'D'),
+                     stringsAsFactors = F)
> test1
  x z
1 b A
2 e B
3 f C
4 x D
> View(test1)
> test2 <- data.frame(x = c('a','b','c','d','e','f'), 
+                     y = c(1,2,3,4,5,6),
+                     stringsAsFactors = F)
> test2 
  x y
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5
6 f 6

 3.1 內连inner_join,取交集

> inner_join(test1, test2, by = "x")
  x z y
1 b A 2
2 e B 5
3 f C 6

 3.2 左连left_join,取交集

> left_join(test1,test2,by="x")
  x z  y
1 b A  2
2 e B  5
3 f C  6
4 x D NA
> left_join(test2,test1,by="x")
  x y    z
1 a 1 <NA>
2 b 2    A
3 c 3 <NA>
4 d 4 <NA>
5 e 5    B
6 f 6    C

 3.3 全连full_join,取合集

> full_join(test2,test1)
Joining, by = "x"
  x  y    z
1 a  1 <NA>
2 b  2    A
3 c  3 <NA>
4 d  4 <NA>
5 e  5    B
6 f  6    C
7 x NA    D

 3.4 半连接:返回能够与y表匹配的x表所有记录semi_join

> semi_join(x = test1, y = test2, by = 'x')
  x z
1 b A
2 e B
3 f C

 3.4 反连接:返回无法与y表匹配的x表的所记录anti_join

> anti_join(x=test2,y=test1,by="x")
  x y
1 a 1
2 c 3
3 d 4

 3.5 简单合并

> test3 <- data.frame(x = c(1,2,3,4), y = c(10,20,30,40))
> test4 <- data.frame(x = c(5,6), y = c(50,60))
> test5 <- data.frame(z = c(100,200,300,400))
> cbind(test3,test5)
  x  y   z
1 1 10 100
2 2 20 200
3 3 30 300
4 4 40 400
> bind_cols(test3,test5)
  x  y   z
1 1 10 100
2 2 20 200
3 3 30 300
4 4 40 400
> bind_rows(test4,test5)
   x  y   z
1  5 50  NA
2  6 60  NA
3 NA NA 100
4 NA NA 200
5 NA NA 300
6 NA NA 400
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,968评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,682评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,254评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,074评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,964评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,055评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,484评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,170评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,433评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,512评论 2 308
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,296评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,184评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,545评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,150评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,437评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,630评论 2 335

推荐阅读更多精彩内容