Tidyverse
《R数据科学》(大神全套体系)
- ggplot2:数据可视化
- dplyr:数据转换和处理数据关系
- readr:数据导入
- stringr:处理字符串
一、tidyr
数据清理,转化为标准表格,tidydata每个变量(variable)占一列,每个观测(observation)占一行
1. 数据清理
test <- data.frame(geneid = paste0("gene",1:4),
sample1 = c(1,4,7,10),
sample2 = c(2,5,0.8,11),
sample3 = c(0.3,6,9,12))
test
(1)扁变长
test_gather <- gather(data = test,
key = sample_nm,
value = exp,
- geneid)
head(test_gather)
(2)长变扁
test_re <- spread(data = test_gather,
key = sample_nm,
value = exp)
head(test_re)
2. 分割和合并
test <- data.frame(x = c( "a,b", "a,d", "b,c"));test
(1)分割
test_seprate <- separate(test,x, c("X", "Y"),sep = ",");test_seprate
(2)合并
test_re <- unite(test_seprate,"x",X,Y,sep = ",")
3. 处理NA
X<-data.frame(X1 = LETTERS[1:5],X2 = 1:5)
X[2,2] <- NA
X[4,1] <- NA
(1)去掉含有NA的行,可以选择只根据某一列来去除
drop_na(X)
drop_na(X,X1)
drop_na(X,X2)
(2)替换NA
replace_na(X$X2,0)
(3)用上一行的值填充NA
fill(X,X2)
完整操作:https://www.rstudio.com/resources/cheatsheets/
二、dplyr
test <- iris[c(1:2,51:52,101:102),]
rownames(test) =NULL
1. 五个基础函数
(1)mutate():新增列
mutate(test, new = Sepal.Length * Sepal.Width)
test$new = test$Sepal.Length * test$Sepal.Width #base包方式
(2)select():按列筛选
- 按列号筛选
select(test,1)
select(test,c(1,5))
- 按列名筛选
select(test,Sepal.Length)
select(test, Petal.Length, Petal.Width)
vars <- c("Petal.Length", "Petal.Width")
select(test, one_of(vars))
- 一组来自tidyselect的有用函数
select(test, starts_with("Petal"))
select(test, ends_with("Width"))
select(test, contains("etal"))
select(test, matches(".t."))
select(test, everything())
select(test, last_col())
select(test, last_col(offset = 1))
- 利用everything() 列名可以重排序
select(test,Species,everything())
(3)filter():筛选行
filter(test, Species == "setosa")
filter(test, Species == "setosa"&Sepal.Length > 5 )
filter(test, Species %in% c("setosa","versicolor"))
(4)arrange():按某一列对整个表格进行排序
arrange(test, Sepal.Length) #默认从小到大排序
arrange(test, desc(Sepal.Length)) #desc即从大到小
arrange(test, desc(Sepal.Width),Sepal.Length) #但两行相同时,亚条件排序
(5)summarise():汇总
对数据进行汇总操作,结合group_by使用实用性强
summarise(test, mean(Sepal.Length), sd(Sepal.Length)) #计算Sepal.Length的平均值和标准差
# 先按照Species分组,计算每组Sepal.Length的平均值和标准差
group_by(test, Species)
tmp = summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))
2. 两个实用技能
(1)管道操作 %>% (cmd/ctr + shift + M)
library(dplyr)
x1 = filter(iris,Sepal.Width>3)
x2 = select(x1,c("Sepal.Length","Sepal.Width" ))
x3 = arrange(x2,Sepal.Length)
colnames(iris)
iris %>%
filter(Sepal.Width>3) %>%
select(c("Sepal.Length","Sepal.Width" ))%>%
arrange(Sepal.Length)
#上一行结果做下一行的主对象
(2)count:统计某列的unique值
count(test,Species) #数据框
table(test$Species) #base包,向量
3. 处理关系数据:将2个表进行连接,注意:不要引入factor
options(stringsAsFactors = F)
test1 <- data.frame(name = c('jimmy','nicker','doodle'),
blood_type = c("A","B","O"))
test1
test2 <- data.frame(name = c('doodle','jimmy','nicker','tony'),
group = c("group1","group1","group2","group2"),
vision = c(4.2,4.3,4.9,4.5))
test2
test3 <- data.frame(NAME = c('doodle','jimmy','lucy','nicker'),
weight = c(140,145,110,138))
merge(test1,test2,by="name")
merge(test1,test3,by.x = "name",by.y = "NAME")
(1)內连inner_join:取交集,相同行,合并列
inner_join(test1, test2, by = "name")
inner_join(test1,test3,by = c("name"="NAME"))
(2)左连left_join:取主表行,合并列,缺失值NA
left_join(test1, test2, by = 'name') #前为主表
left_join(test2, test1, by = 'name')
(3)全连full_join:全两表所有行,合并列
full_join(test1, test2, by = 'name')
(4)半连接:返回能够与y表匹配的x表所有记录,取x与y表相同行,x所有列
semi_join(x = test1, y = test2, by = 'name')
(5)反连接:返回无法与y表匹配的x表的所记录 取x与y表差异行,x所有列
anti_join(x = test2, y = test1, by = 'name')
(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)
三、stringr
x <- "The birch canoe slid on the smooth planks."
x
1. 检测字符串长度
length(x) #向量长度
str_length(x) #字符长度
2. 字符串拆分与组合
str_split(x," ") #列表
x2 = str_split(x," ")[[1]] #取列表
y = c("jimmy 150","nicker 140","tony 152")
str_split(y," ")
str_split(y," ",simplify = T) #simplify后得到矩阵
str_c(x2,collapse = " ") #x2的所有元素按空格“ ”连接在一起
str_c(x2,1234,sep = "+") #两个参数
3. 提取字符串的一部分
str_sub(x,5,9)
4. 大小写转换
str_to_upper(x2)
str_to_lower(x2)
str_to_title(x2)
5. 字符串定位
str_locate(x2,"th")
str_locate(x2,"h")
6. 字符检测
str_detect(x2,"h") #生成与X2等长的逻辑向量,可以取子集
str_starts(x2,"T")
str_ends(x2,"e")
与sum和mean连用,可以统计匹配的个数和比例
sum(str_detect(x2,"h")) #Ture的个数
mean(str_detect(x2,"h")) #Ture占全部的比例
7. 提取匹配到的字符串
str_extract(x2,"th|Th") #|或者,默认提取第一次出
str_extract_all(x2,"o") #列表
str_extract_all(x2,"o",simplify = T) #矩阵,“”空字符串
8. 字符删除
str_remove(x," ") #只删掉第一个
str_remove_all(x," ") #删除所有
str_remove_all(x2,"th")
9. 字符串替换
str_replace(x2,"o","A") #只替换第一个
str_replace_all(x2,"o","A")
结合正则表达式更加强大
条件语句和循环语句
一、条件语句
1.if(){ }
(1)只有if没有else,那么条件是FALSE时就什么都不做,只有一个逻辑值
i = -1
if (i<0) print('up')
if (i>0) print('up')
#理解下面代码
if(!require(tidyr)) install.packages('tidyr')
(2)有else:只有一个逻辑值
i =1
if (i>0){
cat('+') #看看里面是什么内容
} else {
print("-") #向量
}
(3)ifelse:自带循环属性,可以有多个逻辑值,重点!
ifelse(i>0,"+","-")
x=rnorm(3)
ifelse(x>0,"+","-")
(4)多个条件
i = 0
if (i>0){
print('+')
} else if (i==0) {
print('0')
} else if (i< 0){
print('-')
}
ifelse(i>0,"+",ifelse((i<0),"-","0"))
2. switch()
cd = 3
foo <- switch(EXPR = cd,
#EXPR = "aa",
aa=c(3.4,1),
bb=matrix(1:4,2,2),
cc=matrix(c(T,T,F,T,F,F),3,2),
dd="string here",
ee=matrix(c("red","green","blue","yellow")))
foo
二、循环语句
1.f or循环
#**顺便看一下next和break**
x <- c(5,6,0,3)
s=0
for (i in x){
s=s+i
#if(i == 0) next
#if (i == 0) break
print(c(i,s))
}
#x下标循环
x <- c(5,6,0,3)
s = 0
for (i in 1:length(x)){
s=s+x[[i]]
print(c(x[[i]],s))
}
如何将结果存下来?
s = 0
result = list() #先声明是列表,然后往列表里一个一个加元素
for(i in 1:length(x)){
s=s+x[[i]]
result[[i]] = c(x[[i]],s)
}
do.call(cbind,result)
2. while 循环
i = 0
while (i < 5){
print(c(i,i^2))
i = i+1
}
3. repeat 语句
#注意:必须有break
i=0L
s=0L
repeat{
i = i + 1
s = s + i
print(c(i,s))
if(i==50) break
}
4. apply函数
- apply(x,MARGIN,FUN)
- x是数据框/矩阵名
- MARGIN为1表示取行,2表示取列
- FUN是函数
- 对x的每一行/列进行FUN这个函数
- sapply(list,fun) #对列表进行循环
插播
长脚本管理方式
1. 分成多个脚本,每个脚本最后将变量保存到Rdata,下一个脚本开头清空再加载
2. 折叠长代码{}
利用if(F)和if(T),只有if(T)会运行
自己写嵌套代码从外往里写,读别人的嵌套代码从里往外读
实战重点函数
- sort和match
- names
- ifelse和str_detect
- identical
- arrange
- merge和inner_join
- unique和duplicated
R语言遍历、创建、删除文件夹
dir
file.create() file.exists(...)
file.remove()
file.rename(from,to)
file.append(file1, file2)
file.copy(from, to, overwrite = recursive, recursive = FALSE, copy.mode = TRUE, copy.date = FALSE)
file.symlink(from,to)
file.link(from, to)
dir.create('doudou')
unlink("doudou",recursive =T)