2020-11-04 Day 6 R语言学习 郑小西
2020-11-04 本文已影响0人
呆呱呱
安装和加载R包
1.镜像设置
2.安装
R包安装命令是install.packages(“包”)
或者BiocManager::install(“包”)
。
3.加载
下面两个命令均可。
library(包)
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)
dplyr五个基础函数
示例数据选择iris
what is iris?
image.png
iris数据集介绍
鸢尾花(iris)是数据挖掘常用到的一个数据集,包含150种鸢尾花的信息,每50种取自三个鸢尾花种之一(setosa,versicolour或virginica)。每个花的特征用下面的5种属性描述萼片长度(Sepal.Length)、萼片宽度(Sepal.Width)、花瓣长度(Petal.Length)、花瓣宽度(Petal.Width)、类(Species)。
观察这5个变量,我们发现Species是字符变量、非连续,难以直接进行线性分析。故首先应对定义哑变量处理离散变量Species。
1.mutate(),新增列
mutate(test, new = Sepal.Length * Sepal.Width)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species new

2.select(),按列筛选

(1)按列号筛选
select(test,1)
select(test,c(1,5))
select(test,Sepal.Length)

(2)按列名筛选
select(test, Petal.Length, Petal.Width)
vars <- c("Petal.Length", "Petal.Width")
select(test, one_of(vars))

3.filter()筛选行
filter(test, Species == "setosa")
filter(test, Species == "setosa"&Sepal.Length > 5 )
filter(test, Species %in% c("setosa","versicolor"))
结果
image.png
image.png
4.arrange(),按某1列或某几列对整个表格进行排序
arrange(test, Sepal.Length)#默认从小到大排序
arrange(test, desc(Sepal.Length))#用desc从大到小
结果
image.png
5.summarise():汇总
summarise(test, mean(Sepal.Length), sd(Sepal.Length)) # 计算Sepal.Length的平均值和标准差
## 先按照Species分组,计算每组Sepal.Length的平均值和标准差
group_by(test, Species)
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))


dplyr两个实用技能
1:管道操作 %>% (cmd/ctr + shift + M)
image.png
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length), sd(Sepal.Length))
##mean sd 表示返回数据的均值和标准差

2:count统计某列的unique值
count(test,Species)
dplyr处理关系数据
即将2个表进行连接
options(stringsAsFactors = F) #不要把字符串变成因子的意思
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)
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
full_join( test1, test2, by = 'x')

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

5.反连接:返回无法与y表匹配的x表的所记录anti_join
anti_join(x = test2, y = test1, by = 'x')
6.简单合并
在相当于base包里的cbind()函数和rbind()函数;注意,bind_rows()函数需要两个表格列数相同,而bind_cols()函数则需要两个数据框有相同的行数
test1 <- data.frame(x = c(1,2,3,4), y = c(10,20,30,40))
test1
test2 <- data.frame(x = c(5,6), y = c(50,60))
test2
test3 <- data.frame(z = c(100,200,300,400))
test3
bind_rows(test1, test2)
bind_cols(test1, test3)
