R包
1镜像设置
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源
2安装
install.packages("ape")
BiocManager::install("ape")
3浏览
library("ape")
require("ape")
4 ''dplyr''包
新增列 mutate()
> library(dplyr)
> test <- iris[c(1:2,51:52,101:102),]
> mutate(test, new = Sepal.Length * 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()
> select(test,c(1,3)) #按照列号筛选第1和3列
Sepal.Length Petal.Length
1 5.1 1.4
2 4.9 1.4
51 7.0 4.7
52 6.4 4.5
101 6.3 6.0
102 5.8 5.1
> select(test, Petal.Length, Species) #按照列筛选
Petal.Length Species
1 1.4 setosa
2 1.4 setosa
51 4.7 versicolor
52 4.5 versicolor
101 6.0 virginica
102 5.1 virginica
筛选行 filter()
> filter(test, Species %in% c("setosa","versicolor")&Sepal.Length > 5)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 7.0 3.2 4.7 1.4 versicolor
3 6.4 3.2 4.5 1.5 versicolor
按某1列或某几列对整个表格进行排序arrange()
> arrange(test, desc(Petal.Width)) #用desc从大到小,默认为从小到大
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 6.3 3.3 6.0 2.5 virginica
2 5.8 2.7 5.1 1.9 virginica
3 6.4 3.2 4.5 1.5 versicolor
4 7.0 3.2 4.7 1.4 versicolor
5 5.1 3.5 1.4 0.2 setosa
6 4.9 3.0 1.4 0.2 setosa
summarise() 汇总计算 count() 计数
>group_by(test, Species)#根据species分组
> summarise(group_by(test, Species),mean(Petal.Length), sd(Petal.Length),mean(Sepal.Width))#计算分组下的mean和sd
# A tibble: 3 x 4
Species `mean(Petal.Length)` `sd(Petal.Length)` `mean(Sepal.Width)`
<fct> <dbl> <dbl> <dbl>
1 setosa 1.4 0 3.25
2 versicolor 4.6 0.141 3.2
3 virginica 5.55 0.636 3
> count(test,Species) #统计species的unique值
# A tibble: 3 x 2
Species n
<fct> <int>
1 setosa 2
2 versicolor 2
3 virginica 2
dplyr处理关系数据
> inner_join(test1, test2, by = "x") #內连inner_join,取交集
x z y
1 b A 2
2 e B 5
3 f C 6
> left_join(test2, test1, by = 'x') #左连left_join
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') #全连full_join
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') #半连接:返回能够与y表匹配的x表所有记录semi_join
x z
1 b A
2 e B
3 f C
> anti_join(x = test2, y = test1, by = 'x') #反连接:返回无法与y表匹配的x表的所记录anti_join
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))
> test3 <- data.frame(z = c(100,200,300,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) #简单合并bind_rows()函数需要两个表格列数相同,而bind_cols()函数则需要两个数据框有相同的行数
x y z
1 1 10 100
2 2 20 200
3 3 30 300
4 4 40 400
网友评论