## 为方便处理,在数据集中增加一列car ```{r echo=FALSE,warning=FALSE,error=FALSE} library(tidyr) library(dplyr) library(tibble) head(mtcars) mtcars$car <- rownames(mtcars) mtcars <- mtcars[, c(12, 1:11)] ``` ##gather-宽数据转为长数据,类似于reshape2包中的melt函数 ```{r} mtcarsNew <- mtcars%>%gather(attribute,value,-car) #tidyr很好的一点是可以只gather若干列而其他列保持不变。如果你想gather在map和gear之间的所有列而保持carb和car列不变 mtcarsNew <- mtcars%>%gather(attribute,value,mpg:gear) ``` ##spread—长数据转为宽数据,类似于reshape2包中的cast函数 ```{r} mtcarsSpread <- mtcarsNew%>%spread(attribute,value) ``` ##unit—多列合并为一列 ```{r} set.seed(1) date <- as.Date('2016-01-01') + 0:14 hour <- sample(1:24, 15) min <- sample(1:60, 15) second <- sample(1:60, 15) event <- sample(letters, 15) data <- data.frame(date, hour, min, second, event) dataNew <- data%>% unite(datehour,date,hour,sep=' ')%>% unite(datetime,datehour,min,second,sep=':') ``` ##separate—将一列分离为多列 ```{r}