長型和寬型數(shù)據(jù)在數(shù)據(jù)分析中非常常見水由。一般人們看到的以行為樣本以列為變量的數(shù)據(jù)為寬型數(shù)據(jù),非常適合人類查看和理解赛蔫。但是在數(shù)據(jù)分析中砂客,常常需要將數(shù)據(jù)轉(zhuǎn)換成長型數(shù)據(jù)才能便于分析和作圖。將在以下幾個(gè)例子中進(jìn)行理解和介紹呵恢。同時(shí)使用R中不同的三個(gè)包進(jìn)行長寬數(shù)據(jù)的轉(zhuǎn)換鞠值。
我們先建立一個(gè)簡單的數(shù)據(jù)框:
widedata <- data.frame(ID=c(1,1,2,2),
Time=c(1,2,1,2),
x1=c(3,4,5,6),
x2=c(7,8,9,10))
widedata
查看數(shù)據(jù)框如下:
這是寬型數(shù)據(jù),如果還是明白的話渗钉,跟長型數(shù)據(jù)一對比就一目了然了彤恶。
1. 用reshape進(jìn)行數(shù)據(jù)的長寬轉(zhuǎn)換
Wide to long
library(reshape)
(longdata1 <- melt(widedata,id=c("ID","Time")))
(longdata1 <- melt(widedata,id="ID"))
這兩個(gè)數(shù)據(jù)框都是長型數(shù)據(jù),根據(jù)前幾列的信息可以對應(yīng)到最后數(shù)值列的唯一值
reshape包的melt函數(shù)使用相對簡單鳄橘,出了第一個(gè)對象為數(shù)據(jù)框声离,參數(shù)一般只有一個(gè),即id瘫怜,設(shè)為id的變量术徊,變量名在轉(zhuǎn)換過程中不變,但是變量的數(shù)值會在長型數(shù)據(jù)中重復(fù)出現(xiàn)鲸湃。
Long to wide
cast(data, formula = ... ~ variable, fun.aggregate=NULL, ..., margins=FALSE, subset=TRUE, df=FALSE, fill=NULL, add.missing=FALSE, value = guess_value(data))
cast函數(shù)有參數(shù)比較多赠涮,這里只展示基本的參數(shù)子寓,其中formula是設(shè)置如何轉(zhuǎn)換為寬型數(shù)據(jù)的重要參數(shù),不同的formula轉(zhuǎn)換成的數(shù)據(jù)可以通過嘗試進(jìn)行理解和體會笋除。
(widedata1 <- cast(longdata1,ID+Time~variable))
(widedata1 <- cast(longdata1,ID~Time+variable))
(widedata1 <- cast(longdata1,ID~variable+Time))
2. 用reshape2進(jìn)行數(shù)據(jù)的長寬轉(zhuǎn)換
Wide to long
reshape2同時(shí)使用melt函數(shù)進(jìn)行寬到長數(shù)據(jù)的轉(zhuǎn)換斜友,但是參數(shù)略有不同,主要的兩個(gè)參數(shù)是id.vars和measure.vars.
library(reshape2)
(longdata2 <- melt(widedata,id.vars=c("ID","Time"),measure.vars=c("x1","x2")))
得到跟reshape包中melt函數(shù)一樣的結(jié)果垃它。
Long to wide
長型數(shù)據(jù)到寬型數(shù)據(jù)的轉(zhuǎn)換鲜屏,在reshape2中沒有cast函數(shù),根據(jù)處理數(shù)據(jù)的不同類型嗤瞎,用acast(vector/matrix/array)和dcast(dataframe)函數(shù)取代墙歪。
這里我們的數(shù)據(jù)是數(shù)據(jù)框听系,因此使用dcast函數(shù)贝奇,其中的公式跟cast類似。
(widedata2 <- dcast(longdata2,ID+Time~variable))
(widedata2 <- dcast(longdata2,ID~Time+variable))
3. 用tidyr進(jìn)行數(shù)據(jù)的長寬轉(zhuǎn)換
Wide to long
tidyr中的gather函數(shù)靠胜,跟reshape和reshape2中的melt函數(shù)的參數(shù)有較大的改變掉瞳,但是更容易理解。
gather(data, key = "key", value = "value", ..., na.rm = FALSE, convert = FALSE, factor_key = FALSE)
其中的key和value生成新的變量的變量名浪漠,...表示可以要進(jìn)行轉(zhuǎn)換的變量陕习,相當(dāng)于reshape2中melt函數(shù)的measure.vars參數(shù)。直接看例子:
library(tidyr)
(longdata3 <- gather(widedata, key = "variable",value ="value", x1:x2 ))
得到跟上面相同的結(jié)果址愿,這里variable和value是自己命名的该镣,不同于melt是自動(dòng)生成的,相對更易于理解响谓。
Long to wide
tidyr中的spread函數(shù)损合,跟cast類似,不過參數(shù)與gather相對應(yīng)
spread(data, key, value, fill = NA, convert = FALSE, drop = TRUE, sep = NULL)
關(guān)鍵的參數(shù)是key和value娘纷,指定后就可以根據(jù)相應(yīng)的key和value進(jìn)行長到寬的轉(zhuǎn)換
(widedata3 <- spread(longdata3,key = "variable",value = "value"))
總結(jié)
初學(xué)者在使用R時(shí)嫁审,常常對reshape和reshape2有點(diǎn)迷惑,尤其是melt函數(shù)名字一模一樣赖晶,因此容易造成誤解律适,加載了reshape2后發(fā)現(xiàn)cast函數(shù)不能使用。個(gè)人傾向于直接使用gather和spread函數(shù)遏插,直接跳過reshape和reshape2的困擾捂贿。不過理清楚reshape和reshape2的主要區(qū)別,使用起來也不容易混淆胳嘲。