学习小组Day6笔记--pangguanchao
2018-10-13 本文已影响13人
0fdc0b2caa52
一、思维导图

二、准备工作
1. 获取R包小抄(cheatsheet)
(1) 百度、谷歌搜索
(2) Rstudio的cheatsheet网站

(3) 生信星球公众号回复包名
2. tidyr功能
将要用的数据处理成标准而统一的数据框(Tidy Data)
(1) 数据框的变形
(2) 处理数据框中的空值
(3) 根据一个表格衍生出其他表格
(4) 实现行或列的分割和合并
3. 安装R包 install.packages("tidyr")
library(tidyr)

4. 数据框
rep
重复,括号中填要重复的字符和重复次数
paste
连接两个字符串, 括号要填两个代连接字符并指定分隔符sep
, 没有分隔符就填sep=“”
1:3
表示从1到3, 如需一列中需要填入三个无规律的数字, 可以用向量c(1,3,4)
, 同样如果填的是字符串也需要加双引号, 例如c("doudou","huahua","xiaoyu")

5. Tidy Data
一种组织表格数据的方式,提供了一种能够跨包使用的“统一”的数据格式
每个变量(variable)占一列,每个情况(case)和观测值(observation)占一行
image.png
三、tidyr
1. Reshape Data
a<-data.frame(GeneId = rep("gene5",times=3),SampleName =paste("Sample",1:3,sep=""),Expression=c(14,19,18))
gather(a,X1999,X2000,key = "year",value = "cases")

a<-data.frame(GeneId = rep("gene5",times=3),SampleName =paste("Sample",1:3,sep=""),Expression=c(14,19,18))
gather(a,"year","cases",X1999,X2000)

a<-data.frame(GeneId = rep("gene5",times=3),SampleName =paste("Sample",1:3,sep=""),Expression=c(14,19,18))
gather(a,year,cases,-country) #-country的意思就是合并除country外剩下的列

a<-data.frame(GeneId = rep("gene5",times=3),SampleName =paste("Sample",1:3,sep=""),Expression=c(14,19,18))
b <- gather(a,X1999,X2000,key = "year",value = "cases")
spread(b,"year","cases")

2. Handle Missing Values
drop_na() #有空值的, 整行删除掉

fill() #根据上一行的数值填充上

replace_na() #空值填进去特定的一个数值,括号里填数据框名,要填的列名=要填的值

3. Expand Tables
complete(X,nesting(X1),fill=list(X2=5)) #把空值的位置用5补全

complete(X,nesting(X1),fill=list(X2="add relate")) #把空值的位置用add relate补全

pin2<-data.frame(GeneId = rep("gene5",times=3),SampleName =paste("Sample",1:3,sep=""),Expression=c(14,19,18))
expand(pin2,GeneId,SampleName,Expression) #列出每列值所有可能的组合

4. split cells
separate
按列分割, 把一列拆成两列
table3 <- read.csv('table3.txt')
separate(table3,rate,sep="/",into = c("case","pop"))

separate_rows
按行分割,把一列拆成两行
table3 <- read.csv('table3.txt')
separate_rows(table3,rate,sep="/")

unite
分割完了再合并回去
table5 <- read.csv("table5.txt")
unite(table5,century,year,col="year",sep="")
