长型数据和宽型数据在数据分析中非常常见 ,其中宽型数据更具可读性,长型数据则更适合做分析。 R-tidyr主要有以下几大功能:
unit和separate可参考Tidyverse|数据列的分分合合,一分多,多合一,本文主要介绍利用tidyr包实现长宽数据的转化。 一 载入R包,数据 #library(tidyr) #使用mtcars内置数据集 data(mtcars) head(mtcars) 二 宽数据转为长数据
其中 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 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) 三 长数据转为宽数据
data:待转换的长数据 key:需要将变量值拓展为字段的变量 value:需要分散的值 fill:对于缺失值,可将fill的值赋值给被转型后的缺失值 mtcars_wide <- mtcars_long2 %>%spread(variables, values) head(mtcars_wide) 这实际将原来gather后的结果还原为gather前, 结果与mtcars一样,只是各列的相互位置稍有调整。 参考资料:Working_in_the_Tidyverse 【觉得不错,右下角点个“在看”,期待您的转发,谢谢!】
|
|