Nice example of converting wide to tall data with tidyr

Nice example.

> x <- structure(c(1961, 1961, 1961, 1961, 1, 1, 1, 1, 1, 2, 3 
+         , 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 
+         , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 
+         , 28, 29, 30, 31, 32, 33, 34, 35, 36) 
+     , .Dim = c(4L, 12L) 
+     , .Dimnames = list(NULL, c("year", "month", "day", "A", "B", "C" 
+         , "D", "E", "F", "G", "H", "I")) 
+     ) 
> xdf <- as.data.frame(x) 
> xdf 
  year month day A B  C  D  E  F  G  H  I 
1 1961     1   1 1 5  9 13 17 21 25 29 33 
2 1961     1   2 2 6 10 14 18 22 26 30 34 
3 1961     1   3 3 7 11 15 19 23 27 31 35 
4 1961     1   4 4 8 12 16 20 24 28 32 36 
> require(tidyr) 
> require(dplyr) 
> xdf %>% gather(station, discharge, -year, -month, -day) 
   year month day station discharge 
1  1961     1   1       A         1 
2  1961     1   2       A         2 
3  1961     1   3       A         3 
4  1961     1   4       A         4 
5  1961     1   1       B         5 
6  1961     1   2       B         6 
7  1961     1   3       B         7 
8  1961     1   4       B         8 
9  1961     1   1       C         9 
10 1961     1   2       C        10 
11 1961     1   3       C        11 
12 1961     1   4       C        12 
13 1961     1   1       D        13 
14 1961     1   2       D        14 
15 1961     1   3       D        15 
16 1961     1   4       D        16 
17 1961     1   1       E        17 

Leave a Reply

Your email address will not be published. Required fields are marked *