同名公主號:BBio
reshape2包最常用的場景就是長數(shù)據(jù)和寬數(shù)據(jù)的轉(zhuǎn)換网缝,兩個函數(shù)即可搞定什乙。作者也是tidyverse的作者葫笼,Rstudio項(xiàng)目的首席科學(xué)家Hadley Wickham袒餐。reshape2已經(jīng)很久沒有更新了,tidyverse工作流下的tidyr是實(shí)現(xiàn)數(shù)據(jù)轉(zhuǎn)換更好的工具姑尺,不過此處還是簡單介紹一下。
//長數(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)為長數(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ù):長數(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定義解析為值的列
#如果解析的行有多個值怎么辦榆芦?添加運(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對應(yīng)的variable只有一行柄粹,不需要指定運(yùn)算函數(shù)
dcast(aqm, month + day ~ variable)
#month和variable有多個行,指定運(yùn)算函數(shù)匆绣,不然會統(tǒng)計(jì)頻數(shù)
dcast(aqm, month ~ variable, fun.aggregate=mean)