R包入门
镜像设置(必备)
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/")
安装
install.packages(“X”)
或者BiocManager::install(“X”)
具体是哪个安装方式可以从谷歌搜索
运行
library(包)
dplyr五个基础函数
- mutate(),新增列
mutate(test, new = Sepal.Length * Sepal.Width)
- select(),按列筛选
select(test,1)
等等 - filter()筛选行
filter(test, Species == "setosa")
等等 - arrange(),按某1列或某几列对整个表格进行排序
arrange(test, Sepal.Length)#默认从小到大排序
arrange(test, desc(Sepal.Length))#用desc从大到小
- summarise():汇总
summarise(test, mean(Sepal.Length), sd(Sepal.Length))
# 计算Sepal.Length的平均值和标准差
group_by(test, Species)
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))
# 先按照Species分组,计算每组Sepal.Length的平均值和标准差
dplyr两个技能
- 管道操作 %>% (cmd/ctr + shift + M)
- count统计某列的unique值
dplyr处理关系数据
options(stringsAsFactors = F)
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
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
1.inner_join(test1, test2, by = "x")
test1, test2,取交集,以x为准
2.left_join(test1, test2, by = 'x')
左连,以test1中x为准
3.full_join( test1, test2, by = 'x')
全连接
-
semi_join(x = test1, y = test2, by = 'x')
半连接:返回能够与y表匹配的x表所有记录 -
anti_join(x = test2, y = test1, by = 'x')
反连接:返回无法与y表匹配的x表的所记录
6.bind_rows(test1, test2)
简单行合并