reshape2::meltとtidyr::gather

2種類の時系列データx,yがある.

library(dplyr)
## 
## Attaching package: 'dplyr'
## 
##  以下のオブジェクトはマスクされています (from 'package:stats') : 
## 
##      filter, lag 
## 
##  以下のオブジェクトはマスクされています (from 'package:base') : 
## 
##      intersect, setdiff, setequal, union
dat = data.frame(time = 1:10, x = rnorm(10), y=rnorm(10))
dat
##    time       x       y
## 1     1  1.1473 -2.5415
## 2     2  1.2235  0.2028
## 3     3  1.8214  0.8401
## 4     4  1.3995 -1.3296
## 5     5  1.0913 -0.9562
## 6     6  0.4846 -2.0448
## 7     7 -0.1157  1.0566
## 8     8  0.2848  0.5690
## 9     9 -1.4446 -0.2985
## 10   10  2.2048 -2.0180

x,yの様子を重ね書きしたいときを考えます.

reshape2::meltを使う

今まではこうしていました.

library(reshape2)
library(ggplot2)
dat %>% 
  melt(id.var = "time", value.name="value") -> dat_melt

dat_melt %>% 
  ggplot(aes(x=time, y=value, color=variable)) + 
  geom_line(size = 2)

plot of chunk unnamed-chunk-2 ただ, データフレームのサイズが大きくなると遅いです.

tidyr::gatherを使う

Hadley神が開発したtidyrを使いましょう. 今回はtydir::gatherを使います.

library(tidyr)
## Warning: package 'tidyr' was built under R version 3.1.1
dat %>% 
  gather(key = variable, value = value, -time) -> dat_gathered

dat_gathered %>% 
  ggplot(aes(x=time, y=value, color=variable)) + 
  geom_line(size=2)

plot of chunk unnamed-chunk-3

なるほど.