同名公主號(hào):BBio
reshape2包最常用的場(chǎng)景就是長(zhǎng)數(shù)據(jù)和寬數(shù)據(jù)的轉(zhuǎn)換,兩個(gè)函數(shù)即可搞定。作者也是tidyverse的作者,Rstudio項(xiàng)目的首席科學(xué)家Hadley Wickham。reshape2已經(jīng)很久沒(méi)有更新了,tidyverse工作流下的tidyr是實(shí)現(xiàn)數(shù)據(jù)轉(zhuǎn)換更好的工具,不過(guò)此處還是簡(jiǎn)單介紹一下。
//長(zhǎng)數(shù)據(jù):ggplot2繪圖數(shù)據(jù)格式
data <- data.frame(celltype=rep(c("T cells", "B cells"), each=3),
sample=rep(c("S1", "S2", "S3"), 2),
percent=runif(6))
#celltype sample percent
#1 T cells S1 0.9825346
#2 T cells S2 0.3768486
#3 T cells S3 0.8072078
#4 B cells S1 0.8889155
#5 B cells S2 0.8150424
#6 B cells S3 0.5531544
//寬數(shù)據(jù):pheatmap繪圖數(shù)據(jù)格式
data <- data.frame(celltype=c("T cells", "B cells"),
S1=runif(2),
S2=runif(2),
S3=runif(2))
#celltype S1 S2 S3
#1 T cells 0.1704449 0.3704776 0.82863072
#2 B cells 0.6085021 0.5197027 0.09653481
//如何實(shí)現(xiàn)兩者的相互轉(zhuǎn)換?
- melt函數(shù):寬數(shù)據(jù)轉(zhuǎn)為長(zhǎng)數(shù)據(jù)
library(reshape2)
?melt
data <- data.frame(celltype=c("T cells", "B cells"),
S1=runif(2),
S2=runif(2),
S3=runif(2))
#id.vars定義錨點(diǎn),也可以直接寫id
melt(data, id.vars=c("celltype"), variable.name="sample", value.name="percent")
#celltype sample percent
#1 T cells S1 0.17044494
#2 B cells S1 0.60850210
#3 T cells S2 0.37047760
#4 B cells S2 0.51970266
#5 T cells S3 0.82863072
#6 B cells S3 0.09653481
- dcast函數(shù):長(zhǎng)數(shù)據(jù)轉(zhuǎn)為寬數(shù)據(jù)
?dcast
data <- data.frame(celltype=rep(c("T cells", "B cells"), each=3),
sample=rep(c("S1", "S2", "S3"), 2),
percent=runif(6))
dcast(data, celltype ~ sample, value.var="percent")
#如果數(shù)據(jù)有多余的列怎么辦?指定value.var定義解析為值的列
#如果解析的行有多個(gè)值怎么辦?添加運(yùn)算函數(shù)
names(airquality) <- tolower(names(airquality))
aqm <- melt(airquality, id=c("month", "day"), na.rm=TRUE)
head(aqm)
# month day variable value
#1 5 1 ozone 41
#2 5 2 ozone 36
#3 5 3 ozone 12
#4 5 4 ozone 18
#6 5 6 ozone 28
#7 5 7 ozone 23
#month和day對(duì)應(yīng)的variable只有一行,不需要指定運(yùn)算函數(shù)
dcast(aqm, month + day ~ variable)
#month和variable有多個(gè)行,指定運(yùn)算函數(shù),不然會(huì)統(tǒng)計(jì)頻數(shù)
dcast(aqm, month ~ variable, fun.aggregate=mean)