tidyverse包

一、数据框排序

  1. test <- iris[c(1:2,51:52,101:102),]
  2. rownames(test) =NULL
  3. test
  4. # order 可以给向量排序,也可以给数据框排序。x[order(x)]
  5. sort(test$Sepal.Length) #对某列排序
  6. test$Sepal.Length[order(test$Sepal.Length)] #全部排列
  7. test[order(test$Sepal.Length),] #对所有列进行排序,默认升序
  8. test[order(test$Sepal.Length,decreasing = T),] #对所有列进行降序排列
  9. # arrange,更加灵活的排序,整行移动,不加引号
  10. library(dplyr)
  11. arrange(test, Sepal.Length)
  12. arrange(test, desc(Sepal.Length)) #降序排列
  13. arrange(test, desc(Sepal.Width),Sepal.Length)#先按照A排列,如果列相同,按照B列排列
  14. 来自dplyr包的其他函数
  15. #mutate:新增列
  16. mutate(test,new=Sepal.Length*Sepal.Width)
  17. test$new=test$Sepal.Length*test$Sepal.Width#也能新增列
  18. #select()、filter() 筛选行、列
  19. #管道符号 %>%代表向后传递,能规避产生中间变量
  20. x1 = filter(iris,Sepal.Width>3) #筛选行
  21. x2 = select(x1,Sepal.Length,Sepal.Width)#筛选列
  22. x3=arrange(x2,Sepal.Length)
  23. #第二种方法
  24. x = iris %>%
  25. filter(Sepal.Width>3) %>%
  26. select(Sepal.Length,Sepal.Width) %>%
  27. arrange(Sepal.Length)
  28. #第三种方法
  29. arrange(select(filter(iris,Sepal.Width>3),Sepal.Length,Sepal.Width),Sepal.Length)

二、表达矩阵画箱式图

对数据格式进行更改
1、把原有的行名转变为第一列
2、转置T
3、宽变长
image.png

  1. # 表达矩阵的代码操作
  2. set.seed(10086) #设定随机种子,保证随机的结果可重复
  3. exp = matrix(rnorm(18),ncol = 6)
  4. exp = round(exp,2) #保留小数点后2位数
  5. rownames(exp) = paste0("gene",1:3)
  6. colnames(exp) = paste0("test",1:6)
  7. exp[,1:3] = exp[,1:3]+1 #前三列加1
  8. exp
  9. library(tidyr)
  10. library(tibble)
  11. library(dplyr)
  12. dat = t(exp) %>% #转制
  13. as.data.frame() %>%
  14. rownames_to_column() %>%
  15. mutate(group = rep(c("control","treat"),each = 3))
  16. pdat = dat%>%
  17. pivot_longer(cols = starts_with("gene"), #pivot,宽变长的函数
  18. names_to = "gene",
  19. values_to = "count")
  20. library(ggplot2)
  21. p = ggplot(pdat,aes(gene,count))+
  22. geom_boxplot(aes(fill = group))+
  23. theme_bw()
  24. p
  25. p + facet_wrap(~gene,scales = "free")#分为3张子图,scales 参数fixed表示固定坐标轴刻度,free表示反馈坐标轴刻度

三、连接

  1. test1 <- data.frame(name = c('jimmy','nicker','Damon','Sophie'),
  2. blood_type = c("A","B","O","AB"))
  3. test1
  4. test2 <- data.frame(name = c('Damon','jimmy','nicker','tony'),
  5. group = c("group1","group1","group2","group2"),
  6. vision = c(4.2,4.3,4.9,4.5))
  7. test2
  8. library(dplyr)
  9. inner_join(test1,test2,by="name")#交集inner_join
  10. left_join(test1,test2,by="name")#左连接
  11. right_join(test1,test2,by="name")#右连接
  12. full_join(test1,test2,by="name")#全连接
  13. semi_join(test1,test2,by="name")#半连接
  14. anti_join(test1,test2,by="name")#反连接

总结
image.png

  1. # 练习7-1
  2. # 1.加载test1.Rdata,将dat数据框按照logFC从小到大排序
  3. load("test1.Rdata")
  4. library(dplyr)
  5. arrange(dat, logFC)#注意⚠️不加引号
  6. # 2.将test1.Rdata中存放的两个数据框连接在一起,按共同的列取交集
  7. x=merge(dat,ids,by = "probe_id")#第一种方法
  8. library(dplyr)
  9. x2=inner_join(dat,ids,by = "probe_id")#第二种方法

四、字符串

常用函数

字符长度 str_length(x)
拆分 str_split( )
按位置提取字符 str_sub( )
字符检测 str_detect( )
替换 str_replace( )/str_replace_all()
删除 str_remove()/str_remove_all()
  1. > rm(list = ls())
  2. > if(!require(stringr))install.packages('stringr')
  3. > library(stringr)
  4. >
  5. > x <- "The birch canoe slid on the smooth planks."
  6. >
  7. > x
  8. [1] "The birch canoe slid on the smooth planks."
  9. > ###1.检测字符串长度
  10. > str_length(x) #共多少个字符
  11. [1] 42
  12. > length(x) #向量中有多少函数
  13. [1] 1
  14. >
  15. > ###2.字符串拆分
  16. > str_split(x," ")#以空格作为拆分
  17. [[1]]
  18. [1] "The" "birch" "canoe" "slid" "on" "the" "smooth"
  19. [8] "planks."
  20. > x2 = str_split(x," ")[[1]];x2
  21. [1] "The" "birch" "canoe" "slid" "on" "the" "smooth"
  22. [8] "planks."
  23. >
  24. > y = c("jimmy 150","nicker 140","tony 152")
  25. > str_split(y," ")
  26. [[1]]
  27. [1] "jimmy" "150"
  28. [[2]]
  29. [1] "nicker" "140"
  30. [[3]]
  31. [1] "tony" "152"
  32. > str_split(y," ",simplify = T)
  33. [,1] [,2]
  34. [1,] "jimmy" "150"
  35. [2,] "nicker" "140"
  36. [3,] "tony" "152"
  37. >
  38. > ###3.按位置提取字符串
  39. > str_sub(x,5,9)
  40. [1] "birch"
  41. >
  42. > ###4.字符检测
  43. > str_detect(x2,"h")#检验是否含有h
  44. [1] TRUE TRUE FALSE FALSE FALSE TRUE TRUE FALSE
  45. > str_starts(x2,"h")#检验开头是否含有h
  46. [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
  47. > str_ends(x2,"h")#检验结尾是否含有h
  48. [1] FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE
  49. >
  50. > ###5.字符串替换
  51. > str_replace(x2,"o","A") #只替换一个
  52. [1] "The" "birch" "canAe" "slid" "An" "the" "smAoth"
  53. [8] "planks."
  54. > str_replace_all(x2,"o","A")#全部替换
  55. [1] "The" "birch" "canAe" "slid" "An" "the" "smAAth"
  56. [8] "planks."
  57. >
  58. > ###6.字符删除
  59. > str_remove(x," ")#只删除1
  60. [1] "Thebirch canoe slid on the smooth planks."
  61. > str_remove_all(x," ")#全部删除
  62. [1] "Thebirchcanoeslidonthesmoothplanks."
  63. >

五、条件语句和循环语句

image.png

  1. > rm(list = ls())
  2. >
  3. > ## 一.条件语句
  4. >
  5. > ###1.if(){ }
  6. >
  7. > #### (1)只有if没有else,那么条件是FALSE时就什么都不做
  8. >
  9. > i = -1
  10. > if (i<0) print('up')
  11. [1] "up"
  12. > if (i>0) print('up')
  13. >
  14. > #理解下面代码
  15. > if(!require(tidyr)) install.packages('tidyr')
  16. >
  17. > #### (2)有else,ifelse(x,yes,no)
  18. #3个参数,x逻辑值,yes逻辑值为TRUE的返回值,no逻辑值为FALSE的返回值
  19. > i =1
  20. > if (i>0){
  21. + print('+')
  22. + } else {
  23. + print("-")
  24. + }
  25. [1] "+"
  26. >
  27. > ifelse(i>0,"+","-")
  28. [1] "+"
  29. >
  30. > x=rnorm(3)
  31. > ifelse(x>0,"+","-")
  32. [1] "-" "+" "+"
  33. >
  34. >
  35. > #### (3)多个条件
  36. > i = 0
  37. > if (i>0){
  38. + print('+')
  39. + } else if (i==0) {
  40. + print('0')
  41. + } else if (i< 0){
  42. + print('-')
  43. + }
  44. [1] "0"
  45. >
  46. > ifelse(i>0,"+",ifelse(i<0,"-","0"))#第二种写法
  47. [1] "0"
  48. >
  49. >

循环语句
image.png
image.png
image.png

image.png

  1. ## 二、循环语句
  2. >
  3. > ### 1.for循环
  4. > x <- c(5,6,0,3)
  5. > s=0
  6. > for (i in x){
  7. + s=s+i
  8. + print(c(i,s))
  9. + }
  10. [1] 5 5
  11. [1] 6 11
  12. [1] 0 11
  13. [1] 3 14
  14. >
  15. > x <- c(5,6,0,3)
  16. > s = 0
  17. > for (i in 1:length(x)){
  18. + s=s+x[[i]]
  19. + print(c(x[[i]],s))
  20. + }
  21. [1] 5 5
  22. [1] 6 11
  23. [1] 0 11
  24. [1] 3 14
  25. >
  26. > #如何将结果存下来?
  27. > s = 0
  28. > result = list()
  29. > for(i in 1:length(x)){
  30. + s=s+x[[i]]
  31. + result[[i]] = c(x[[i]],s)
  32. + }
  33. > result
  34. [[1]]
  35. [1] 5 5
  36. [[2]]
  37. [1] 6 11
  38. [[3]]
  39. [1] 0 11
  40. [[4]]
  41. [1] 3 14
  42. > do.call(cbind,result)
  43. [,1] [,2] [,3] [,4]
  44. [1,] 5 6 0 3
  45. [2,] 5 11 11 14
  46. >

六、隐式循环

如何挑出一个表达矩阵里方差最大的1000个基因?
image.png

  1. a=rnorm(100)
  2. sort(a)
  3. tail(sort(a),10)#排序后,取倒数10
  4. load("test2.Rdata")
  5. b=apply(test,1,var)#取方差
  6. x=names(tail(sort(b),1000))
  7. head(x)
  1. > rm(list = ls())
  2. > ## apply()族函数
  3. >
  4. > ### 1.apply 处理矩阵或数据框
  5. >
  6. > #apply(X, MARGIN, FUN, …)
  7. > #其中X是数据框/矩阵名;
  8. > #MARGIN为1表示行,为2表示列,FUN是函数
  9. >
  10. > test<- iris[1:6,1:4]
  11. >
  12. > apply(test, 2, mean)
  13. Sepal.Length Sepal.Width Petal.Length Petal.Width
  14. 4.9500000 3.3833333 1.4500000 0.2333333
  15. >
  16. > apply(test, 1, sum)
  17. 1 2 3 4 5 6
  18. 10.2 9.5 9.4 9.4 10.2 11.4
  19. >
  20. > ### 2.lapply(list, FUN, …) ,列表的隐式循环
  21. > # 对列表/向量中的每个元素(向量)实施相同的操作
  22. >
  23. > test <- list(x = 36:33,y = 32:35,z = 30:27);test
  24. $x
  25. [1] 36 35 34 33
  26. $y
  27. [1] 32 33 34 35
  28. $z
  29. [1] 30 29 28 27
  30. >
  31. > #返回值是列表,对列表中的每个元素(向量)求均值(试试方差var,分位数quantile)
  32. >
  33. > lapply(test,mean)
  34. $x
  35. [1] 34.5
  36. $y
  37. [1] 33.5
  38. $z
  39. [1] 28.5
  40. > lapply(test,fivenum)
  41. $x
  42. [1] 33.0 33.5 34.5 35.5 36.0
  43. $y
  44. [1] 32.0 32.5 33.5 34.5 35.0
  45. $z
  46. [1] 27.0 27.5 28.5 29.5 30.0
  47. > ### 3.sapply 简化结果,直接返回矩阵或向量
  48. >
  49. > sapply(test,mean)
  50. x y z
  51. 34.5 33.5 28.5
  52. > sapply(test,fivenum)
  53. x y z
  54. [1,] 33.0 32.0 27.0
  55. [2,] 33.5 32.5 27.5
  56. [3,] 34.5 33.5 28.5
  57. [4,] 35.5 34.5 29.5
  58. [5,] 36.0 35.0 30.0
  59. >
  60. > class(sapply(test,fivenum))
  61. [1] "matrix" "array"
  62. >
  1. #练习7-2----
  2. # 1.读取group.csv,从第二列中提取圈出来的信息
  3. library(stringr)
  4. a = read.csv("group.csv")
  5. g = str_split(a$title," ",simplify = T)
  6. g
  7. g[,4]
  8. # 2.如何把上一题结果中的Control和Vemurafenib改成全部小写?搜索一下
  9. tolower(g[,4])
  10. str_to_lower(g[,4])
  11. # 3.加载deg.Rdata,根据a、b两列的值,按照以下条件生成向量x:
  12. #a< -1 且b<0.05,则x对应的值为down;
  13. #a>1 且b<0.05,则x对应的值为up;
  14. #其他情况,x对应的值为no
  15. # 统计up、down、no各重复了多少次
  16. load("deg.Rdata")
  17. k1 = deg$a< -1 & deg$b<0.05;table(k1)
  18. k2 = deg$a>1 & deg$b<0.05;table(k2)
  19. x = ifelse(k1,"down",ifelse(k2,"up","no"))

彩蛋:长脚本的管理

第一种方法 利用save和load进行长脚本的管理
image.png
第二种方法,用if
image.png