R----tidyr包介绍学习

R----tidyr包介绍学习 - Little_Rookie - 博客园
https://www.cnblogs.com/nxld/p/6060533.html

# 1.载入包
# 使用datasets包中的mtcars数据集做演示
library(tidyr)
library(dplyr)
head(mtcars)
# 为方便处理,在数据集中增加一列car
mtcars$car <- rownames(mtcars)    
mtcars <- mtcars[, c(12, 1:11)]   #将添加的一列从最后一列移到最前列
head(mtcars)

# 2.gather--宽数据转为长数据
# 除了car列外,其余列聚合成两列,分别命名为attribute和value
mtcarsNew <- mtcars %>% gather(attribute, value, -car) %>% tibble()
head(mtcarsNew)
tail(mtcarsNew)
mtcarsNew$attribute %>% unique() %>% sort()
mtcarsNew$attribute %>% table()
mtcarsNew$attribute %>% table() %>% pie()
# gather在map和gear之间的所有列,而保持carb和car列不变
mtcarsNew <- mtcars %>% gather(attribute, value, mpg:gear)
head(mtcarsNew)

Guess you like

Origin blog.csdn.net/weixin_42683052/article/details/121106172