R_reshape の変更点 - アールメカブ

アールメカブ


R_reshape の変更点


[[Rの備忘録]]

たまたま質問を受けたので.

こういうデータがあるとして

 x <- matrix( c(1920, -47, -67, -13, -60, -89, -34, -29, -59, 53,  
 > x <- matrix( c(1920, -47, -67, -13, -60, -89, -34, -29, -59, 53,  
 -50, 54, 52, 1921, 56, 119, 112, 37, 89, 72, 62, 41, 54, 26, -49, 
 70, 1922, 32, 80, 76, 42, -27, 69, 40, -3, 56, 28, 33, 123, 1923, 
 23, 88, 7, 116, -51, -41, -21, -14, 0, -52, -50,  27, 1924, -108, 
 121,  34, 77, 28, 70, 64, 43, 21, 34, 72, 27), nrow = 5, byrow = T )
 x <- as.data.frame(x)
 colnames(x) <- c( "Year", "JAN","FEB","MAR","APR"," MAY",  
 > x <- as.data.frame(x)
 > colnames(x) <- c( "Year", "JAN","FEB","MAR","APR"," MAY",  
                    "JUN","JUL","AUG","SEP","OCT","NOV","DEC")

 > x
   Year  JAN FEB MAR APR  MAY JUN JUL AUG SEP OCT NOV DEC
 1 1920  -47 -67 -13 -60  -89 -34 -29 -59  53 -50  54  52
 2 1921   56 119 112  37   89  72  62  41  54  26 -49  70
 3 1922   32  80  76  42  -27  69  40  -3  56  28  33 123
 4 1923   23  88   7 116  -51 -41 -21 -14   0 -52 -50  27
 5 1924 -108 121  34  77   28  70  64  43  21  34  72  27

これを縦長に変換する.

 > y <- reshape(x, varying = list(names(x)[-1]), idvar = "Year", 
         dir = "long", v.names = "x", times = colnames(x)[-1] )
 > y <- y[order(y$Year), ]
 > y
           Year time    x
 1920.JAN  1920  JAN  -47
 1920.FEB  1920  FEB  -67
 1920.MAR  1920  MAR  -13
 1920.APR  1920  APR  -60
 1920. MAY 1920  MAY  -89
 1920.JUN  1920  JUN  -34
 1920.JUL  1920  JUL  -29
 1920.AUG  1920  AUG  -59
 1920.SEP  1920  SEP   53
 1920.OCT  1920  OCT  -50
 1920.NOV  1920  NOV   54
 1920.DEC  1920  DEC   52
 1921.JAN  1921  JAN   56
 1921.FEB  1921  FEB  119
 1921.MAR  1921  MAR  112
 ...
 ...
 ...