數(shù)據(jù)框的塑形是學(xué)習(xí)R語(yǔ)言過(guò)程中的一個(gè)重要的知識(shí)點(diǎn)溯泣,是從Excel思維轉(zhuǎn)換成編程思維的重要過(guò)程。盡管很多作圖函數(shù)一個(gè)命令就可以讓輸入數(shù)據(jù)變成美輪美奐的圖,但往往初學(xué)者會(huì)卡在如何制作符合需要的input data上面。根源原因就是Excel的數(shù)據(jù)儲(chǔ)存思維與R語(yǔ)言有很大不同絮姆。很多時(shí)候日常記錄在Excel里面的數(shù)據(jù)格式不適合直接用,而在Excel里面“點(diǎn)點(diǎn)點(diǎn)和調(diào)調(diào)調(diào)”又非常違背學(xué)習(xí)R語(yǔ)言的“懶人精神”赞赖。所以為了節(jié)省下“點(diǎn)點(diǎn)點(diǎn)和調(diào)調(diào)調(diào)”的枯燥時(shí)間滚朵,就要花時(shí)間學(xué)習(xí)一下數(shù)據(jù)塑形。
本文要介紹的2個(gè)包3對(duì)函數(shù)都出自哈德利大神前域。一般人寫(xiě)包就是只是造個(gè)工具,大神直接定義了一種數(shù)據(jù)轉(zhuǎn)換的思維韵吨。直接上表格匿垄,用眼睛體會(huì)一下表格的“長(zhǎng)”和“扁”,省去大段文字描述。
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
我先不說(shuō)這個(gè)test它是個(gè)“扁”表格椿疗,因?yàn)楫?dāng)我把它變“長(zhǎng)”了漏峰,就能感受到它的“扁”了。
# 先不用管這里的包和函數(shù)届榄,體會(huì)表格
library(tidyr)
gather(data = test,
key = sample_nm,
value = exp,
- geneid)
數(shù)據(jù)框“扁”變“長(zhǎng)”就是將所有觀測(cè)值匯總成了一列浅乔,所有變量名也匯總成列。因?yàn)镽語(yǔ)言數(shù)據(jù)處理的時(shí)候基本都是取列(向量)來(lái)用的铝条,具體列里面的元素取哪些靖苇,就靠篩選了。所以要變成這樣班缰。
reshape2 —— melt & dcast
我盲猜這個(gè)包是最先出現(xiàn)的贤壁,因?yàn)榘锩娴暮瘮?shù)最少,文檔里面有這樣一句話:
Reshape (hopefully) makes it easy to do what you have been struggling to do with tapply, by,
aggregate
,xtabs
,apply
andsummarise
. It is also useful for getting your data into the correct structure for lattice or ggplot plots.
感覺(jué)它就是為ggplot
應(yīng)運(yùn)而生的埠忘。它倆還一起獲得了2006年的 John Chambers Award for Statistical Computing獎(jiǎng)項(xiàng)脾拆。盡管現(xiàn)在用的都是ggplot2
了,但這些舊的包和函數(shù)都和好用莹妒,生命力旺盛著呢名船。這三對(duì)函數(shù)之間沒(méi)有巨大差別,細(xì)微之處遇見(jiàn)的比較少旨怠,選哪個(gè)包帚,順手就是好的
melt 變長(zhǎng)
melt基本語(yǔ)法是:
melt(data,id.vars,measure.vars,variable.name='variable',...,na.rm=FALSE,value.name='value',factorAsStrings=TRUE)
只需要記住前三個(gè)變量,后面的都不用管:
-
data
:指的你想處理的數(shù)據(jù)框 -
id.vars
:是不想融合的變量运吓,可以是一個(gè)也可以是多個(gè)(括在向量里) -
measure.vars
:想要融合的變量 -
variable.name
&value.name
:默認(rèn)會(huì)把融合的變量名儲(chǔ)存的列的列名定義為“variable”渴邦,而觀測(cè)值的列名定義為“value”,有了這兩個(gè)參數(shù)拘哨,可以在融合時(shí)就修改成自己想要的名字谋梭。
library(reshape2)
test_melt <- melt(test,id.vars = "geneid",measure.vars = c("sample1","sample2","sample3"))
dcast 變扁
“長(zhǎng)”變“扁”用的是dcast()
函數(shù),語(yǔ)法是:
dcast(data, formula, fun.aggregate = NULL, ..., margins = NULL,
subset = NULL, fill = NULL, drop = TRUE, value.var = guess_value(data))
其中需要掌握的是參數(shù)formula的格式
rowvar1 + rowvar2 +... ~ colvar1 + colvar2 +...
按照rowvar倦青,展開(kāi)colvar瓮床。也可以理解為rowvar是不變的,colvar是拆分的
我們?cè)囋噷⒆兓臄?shù)據(jù)再恢復(fù)产镐。和原始數(shù)據(jù)比較一下隘庄,是一樣的。
test_dcast <- dcast(test_melt, geneid ~ variable)
test_dcast
identical(test, test_dcast)
dcast很棒的功能——聚合運(yùn)算
dcast有一個(gè)很棒的功能就是可以在聚合的時(shí)候(dcast稱為聚合的過(guò)程)可以同步對(duì)數(shù)據(jù)執(zhí)行函數(shù)運(yùn)算癣亚。
- fun.aggregate:用于指定聚合函數(shù)丑掺,對(duì)已聚合的數(shù)據(jù)執(zhí)行聚合運(yùn)算
演示的時(shí)候由于test沒(méi)有相同的分組,所以我們加一列type述雾。
x = test
x$type = rep(c("A","B"),2)
x
可以看到重塑以后的數(shù)據(jù)對(duì)各列按照type進(jìn)行了均值(mean)計(jì)算街州。
x_melt = melt(x,id.vars = c("geneid","type"),measure.vars = c("sample1","sample2","sample3"))
dcast(x_melt, type ~ variable, mean)
tidyr —— gather & spread
tidyr
是哈德利大神的神作tidyverse
中的成員兼丰。專注數(shù)據(jù)框整理,除了gather
和spread
還有許多別的函數(shù)唆缴。這里只關(guān)注這兩個(gè)函數(shù)鳍征。
gather 變長(zhǎng)
這對(duì)函數(shù)開(kāi)始提出了key和value的概念。key就是由變量名組成的一列面徽,相當(dāng)于melt
里面的id.vars
艳丛。value就是觀測(cè)值,相當(dāng)于measure.vars
趟紊。對(duì)于不想變化的列氮双,就在列名前面加一個(gè)"-"(減號(hào))。
用法是:
gather(data,key = "key", value = "value", ..., na.rm = FALSE, convert = FALSE, factor_key = FALSE)
test_gather <- gather(data = test,
key = sample_nm,
value = exp,
- geneid)
test_gather
spread 變扁
用法是:
spread(data, key, value, fill = NA, convert = FALSE, drop = TRUE, sep = NULL)
演示一下test數(shù)據(jù)织阳,和原始數(shù)據(jù)比較果然也是一樣的眶蕉。
test_spread <- spread(data = test_gather,
key = sample_nm,
value = exp)
test_spread
identical(test,test_spread)
注意到spread
里面有個(gè)fill
參數(shù),是處理NA值的唧躲,默認(rèn)是給填上"NA"造挽。
test_na <- test_gather[c(1:2,5:11),]
test_na_re <- spread(data = test_na,
key = sample_nm,
value = exp)
test_na_re # 賦值為NA
# 也可以填上別的,字符串弄痹,一個(gè)確定的數(shù)字都可以
test_na_fill <- spread(data = test_na,
key = sample_nm,
value = exp,
fill = "AAA")
參數(shù)drop
和gather
里面的na.rm
一樣饭入,就是對(duì)于有缺失的觀測(cè)值是否顯示。
melt
和gather
的比較
我們來(lái)比較一下melt
和gather
的結(jié)果肛真。
colnames(test_melt) <- colnames(test_gather) # 列名不一致先處理一下
identical(test_gather,test_melt)
結(jié)果是不一樣的谐丢,很意外吧。肉眼上是完全看不出來(lái)的
test_gather
test_melt
str
一下能看出來(lái)蚓让,數(shù)據(jù)的格式不一樣乾忱。gather
將匯總的變量名處理成字符型,而melt
處理成因子型(即使是在options(stringsAsFactors = FALSE)
的大環(huán)境下)历极,這樣作圖的時(shí)候就會(huì)產(chǎn)生影響窄瘟,所以個(gè)人覺(jué)得gather
會(huì)更好用一些,當(dāng)需要變因子的時(shí)候趟卸,再手動(dòng)調(diào)整蹄葱,也可以自定義因子的順序。
tidyr —— pivot_longer & pivot_wider
在查看gather
幫助文檔的時(shí)候會(huì)發(fā)現(xiàn)這個(gè)包的狀態(tài)是“retired”锄列。盡管并不影響我們對(duì)這個(gè)包的熱愛(ài)和使用图云,但好奇心驅(qū)使我去查看了文檔底下推薦的pivot,然后就看到了大神對(duì)自己包的官方吐槽邻邮。
For some time, it’s been obvious that there is something fundamentally wrong with the design of spread() and gather(). Many people don’t find the names intuitive and find it hard to remember which direction corresponds to spreading and which to gathering. It also seems surprisingly hard to remember the arguments to these functions, meaning that many people (including me!) have to consult the documentation every time.
他們的用法如下竣况,只保留了重要參數(shù)。詳細(xì)的參見(jiàn)vignette
pivot_longer(
data,
cols,
names_to = "name",
values_to = "value")
pivot_wider(
data,
id_cols = NULL,
names_from = name,
values_from = value)
這兩對(duì)函數(shù)和gather & spread沒(méi)有本質(zhì)區(qū)別饶囚,只是讓參數(shù)“說(shuō)人話”了,使用起來(lái)更友好了一些叶堆。所以對(duì)應(yīng)的參數(shù)名稱是:
gather & spread | pivot_X |
---|---|
key | names_to |
value | values_to |
key | names_from |
value | values_from |
其他資料
另外看到了一篇文章關(guān)于tidyr和reshape2的比較。https://rpubs.com/sterding/Reshape2_and_Tidyr
Tidyr vs. Reshape2
- They are very similar!
- cast() in reshape2 can work on matrix/array, while gather() in tidyr can only work on data.frame.
- reshape2 can do aggregation, while tidyr is not designed for this purpose.
- colsplit() in reshape2 operates only on a single column while separate() in tidyr performs all the operation at once.