学习R包 包治百病
R包下载地址镜像设置
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/")
options()$BioC_mirror查看是否设置成功
R包安装命令是install.packages(' ')或者BiocManager::install(' ')
加载R包library() require()
dplyr五个基础函数
示范数据使用内置数据的子集
test<-iris[c(1:2,51:52,101:102),]

Snipaste_2020-02-24_13-29-59.png
新增
使用mutate新增列
> mutate(test,new=test$Sepal.Length*test$Sepal.Width)
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筛选列
> vars<-c("Petal.Length", "Petal.Width")
> select(test,one_of(vars))
Petal.Length Petal.Width
1 1.4 0.2
2 1.4 0.2
51 4.7 1.4
52 4.5 1.5
101 6.0 2.5
102 5.1 1.9
使用filter筛选行
> filter(test, Species == "setosa"&Sepal.Length > 5 )
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
排序
使用arrange按照某列对表格进行排序
> arrange(test,desc(Sepal.Length))
#desc表示倒序,默认由小到大
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 7.0 3.2 4.7 1.4 versicolor
2 6.4 3.2 4.5 1.5 versicolor
3 6.3 3.3 6.0 2.5 virginica
4 5.8 2.7 5.1 1.9 virginica
5 5.1 3.5 1.4 0.2 setosa
6 4.9 3.0 1.4 0.2 setosa
数据汇总
> test%>% #管道操作需先加载tidyverse包
+ group_by(Species)%>%
+ summarise(mean(Sepal.Length),sd(Sepal.Length))
# 先按照Species分组,计算每组Sepal.Length的平均值和标准差
# A tibble: 3 x 3
Species `mean(Sepal.Length)` `sd(Sepal.Length)`
<fct> <dbl> <dbl>
1 setosa 5 0.141
2 versicolor 6.7 0.424
3 virginica 6.05 0.354
dplyr处理数据关系
数据准备
test1 <- data.frame(x = c('b','e','f','x'),
+ z = c("A","B","C",'D'),
+ stringsAsFactors = F)
test2 <- data.frame(x = c('a','b','c','d','e','f'),
+ y = c(1,2,3,4,5,6),
+ stringsAsFactors = F)
各种join之间的关系,只可意会不可言传X
>inner_join(test1,test2,by='x')
#两个数据集取交集
x z y
1 b A 2
2 e B 5
3 f C 6
> left_join(test2, test1, by = 'x')
#以test2的x为主,将test1连接上去
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
> full_join( test1, test2, by = 'x')
#将两个数据集组合起来,仔细观察fulljoin里有x=x这一情况,而leftjoin里没有
x z y
1 b A 2
2 e B 5
3 f C 6
4 x D NA
5 a <NA> 1
6 c <NA> 3
7 d <NA> 4
> semi_join(x = test1, y = test2, by = 'x')
#将存在于test2中的x从test1中取出来,观察与innerjoin的区别
x z
1 b A
2 e B
3 f C
> anti_join(x = test2, y = test1, by = 'x')
x y
1 a 1
2 c 3
3 d 4
简单合并
> test1 <- data.frame(x = c(1,2,3,4), y = c(10,20,30,40))
> test2 <- data.frame(x = c(5,6), y = c(50,60))
> bind_rows(test1,test2) #bindrows需要列数相同
x y
1 1 10
2 2 20
3 3 30
4 4 40
5 5 50
6 6 60
> test3 <- data.frame(z = c(100,200,300,400))
> bind_cols(test1, test3) #bindcols需要行数相同
x y z
1 1 10 100
2 2 20 200
3 3 30 300
4 4 40 400