学习R包
安装和加载R包
1.镜像设置
https://mp.weixin.qq.com/s/XvKb5FjAGM6gYsxTw3tcWw来自生信星球
2.安装
R包安装命令是install.packages(“包”)或者BiocManager::install(“包”)。取决于你要安装的包存在于CRAN网站还是Biocductor
3.加载
library(包)
require(包)

dplyr五个基础函数
示例数据直接使用内置数据集iris的简化版
test <- iris[c(1:2,51:52,101:102),]
1.mutate(),新增列

代表新增了一列名为“new”的数值,数值为sepal.legth*sepal.width
2.select(),按列筛选
(1)按列号筛选

(2)按列名筛选

3.filter()筛选行

4.arrange(),按某1列或某几列对整个表格进行排序
arrange(test, Sepal.Length)
默认从小到大排序
arrange(test, desc(Sepal.Length))
用desc从大到小
5.summarise():汇总
summarise(test, mean(Sepal.Length), sd(Sepal.Length))
计算Sepal.Length的平均值和标准差先按照Species分组,计算每组Sepal.Length的平均值和标准差
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))

dplyr两个实用技能
1:管道操作 %>% (cmd/ctr + shift + M)
(加载任意一个tidyverse包即可用管道符号)
注:tidyverse是一组处理与可视化R包的集合,其中ggplot2与dplyr最广为人知
符号%>%,其意思是将%>%左边的对象传递给右边的函数
test %>% group_by(Species) %>% summarise(mean(Sepal.Length),sd(Sepal.Length))

2:count统计某列的unique值
count(test,Species)

dplyr处理关系数据
即将2个表进行连接,注意:不要引入factor
options(stringsAsFactors = F)
代表禁止将字符转换为factor

1.內连inner_join,取交集
inner_join(test1, test2, by = "x")

2.左连left_join
left_join(test1, test2, by = 'x')
left_join(test2, test1, by = 'x')

3.全连full_join

4.半连接:返回能够与y表匹配的x表所有记录semi_join
semi_join(x, y): 保留 x 表中与 y 表中的观测相匹配的所有观测。
semi_join(x = test1, y = test2, by = 'x')

semi_join函数所得结果为与inner_join类似,同样是求两个数据集的交集,但semi_join只保留/返回前者与后者相匹配的函数
5.反连接:返回无法与y表匹配的x表的所记录anti_join
anti_join(x, y): 丢弃 x 表中与 y 表中的观测相匹配的所有观测。
anti_join(x = test2, y = test1, by = 'x')


6.简单合并
相当于base包里的cbind()函数和rbind()函数;注意,bind_rows()函数需要两个表格列数相同,而bind_cols()函数则需要两个数据框有相同的行数
- cbind: 根据列进行合并,即叠加所有列,m列的矩阵与n列的矩阵cbind()最后变成m+n列,合并前提:cbind(a, b)中矩阵a、b的行数必需相符
-
rbind: 根据行进行合并,就是行的叠加,m行的矩阵与n行的矩阵rbind()最后变成m+n行,合并前提:rbind(a, b)中矩阵a、b的列数必需相符
网友评论