学习小组Day6笔记--潘潘
2021-06-16 本文已影响0人
三点水的番薯
学习R包
思维导图

1. 安装和加载R包
安装:install.packages(“包”)
OR BiocManager::install(“包”)
。
加载:library(包)
OR require(包)
。
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源
install.packages("dplyr")
library(dplyr)
2. dplyr五个基础函数
dplyr包主要用于数据清洗和整理,主要功能包括:行选择、列选择、统计汇总、窗口函数,数据框交集等。
(1)新增列 mutate()
。

(2)按列筛选
select()
。
①按照列号筛选
②按照列命筛选
(3)按行筛选
filter()

(4)按某一列或某几列对整个表格进行排序
arrange()
,默认是从小到大,加入desc()
是从大到小。
(5)汇总summarise()
,对数据进行汇总,结合group_by()
。
group_by()
这个函数用来定义分组变量,并没有直接改变数据的结构。
summarise()
n()、n_distinct(x)#计数
mean(x)、median(x)#中间值
sd()、mad(x)、IQR(X)#离散程度
quartile()、min(x)、max(x)#极端值
first()、last()、nth()#位置

3. dplyr两个实用技能
(1)管道操作%>%
管道命令:在linux中,管道命令|
仅能处理经由前面一个命令传来的正确信息。也就是standard output的信息。

(2)统计某列的unique值count()
4. dplyr处理数据关系
注意:不要引入factor
(1)取两个列表的交集inner_join

(2)左连
left_join

(3)全连
full_join

(4)返回能够与y表匹配的x表所有记录,半连接
semi_join

(5)返回无法与y表匹配的x表的所记录,反连接
anti_join

(6)简单合并:在相当于base包里的cbind()函数和rbind()函数;注意,bind_rows()函数需要两个表格列数相同,而bind_cols()函数则需要两个数据框有相同的行数。
test1 <- data.frame(x = c(1,2,3,4), y = c(10,20,30,40))
test1
## x y
## 1 1 10
## 2 2 20
## 3 3 30
## 4 4 40
test2 <- data.frame(x = c(5,6), y = c(50,60))
test2
## x y
## 1 5 50
## 2 6 60
test3 <- data.frame(z = c(100,200,300,400))
test3
## z
## 1 100
## 2 200
## 3 300
## 4 400
bind_rows(test1, test2)
## x y
## 1 1 10
## 2 2 20
## 3 3 30
## 4 4 40
## 5 5 50
## 6 6 60
bind_cols(test1, test3)
## x y z
## 1 1 10 100
## 2 2 20 200
## 3 3 30 300
## 4 4 40 400
代码来自于生信星球公众号