長型數據和寬型數據在數據分析中非常常見 ,其中寬型數據更具可讀性,長型數據則更適合做分析。
R-tidyr主要有以下幾大功能:
gather—寬數據轉為長數據;
spread—長數據轉為寬數據;
unit—多列合併為一列;
separate—將一列分離為多列
unit和separate可參考Tidyverse|數據列的分分合合,一分多,多合一,本文主要介紹利用tidyr包實現長寬數據的轉化。
library(tidyverse)
#library(tidyr)
#使用mtcars內置數據集
data(mtcars)
head(mtcars)
使用gather函數:gather(data, key, value, … , na.rm = FALSE, convert = FALSE)
其中 data:為待轉換的寬數據
key:將原數據框中的所有列賦給一個新變量key
value:將原數據框中的所有值賦給一個新變量value
...:可以指定哪些列聚到一列中 (同reshape2區別)
na.rm:是否刪除缺失值
1 轉換全部列#寬轉長
mtcars_long <- mtcars %>%
rownames_to_column("car_ID") %>%
gather(key = "variables", value = "values")
head(mtcars_long)
2 部分列保持不變區別於reshape2,...只將指定變量從寬數據變成長數據
1) 不gather car_ID列 (行名轉化而來)
mtcars_long2 <- mtcars %>%
rownames_to_column("car_ID") %>%
gather(key = "variables", value = "values", - car_ID)
head(mtcars_long2)2)gather 在 mpg:am之間的所有列
mtcars_long3 <- mtcars %>%
rownames_to_column("car_ID") %>%
gather(key = "variables", value = "values", mpg:am)
head(mtcars_long3)
使用spread函數:spread(data, key, value, fill = NA, convert = FALSE, drop = TRUE)
data:待轉換的長數據
key:需要將變量值拓展為欄位的變量
value:需要分散的值
fill:對於缺失值,可將fill的值賦值給被轉型後的缺失值
mtcars_wide <- mtcars_long2 %>%
spread(variables, values)
head(mtcars_wide)
這實際將原來gather後的結果還原為gather前, 結果與mtcars一樣,只是各列的相互位置稍有調整。
參考資料:Working_in_the_Tidyverse
【覺得不錯,右下角點個「在看」,期待您的轉發,謝謝!】