tidyr はデータフレーム(正確には tibble 型のオブジェクト)の並べ方を展開したり、集約したりする際に利用する関数が多く用意されている。reshape2 パッケージの改良版という位置付けである。tidyr パッケージの機能を説明するために、iris のデータセットを使用する。このデータセットは、次のように 150 行 5 列からなるデータフレームである。
iris <- read.table('data/iris.txt', header = TRUE, sep = '\t')
head(iris)
## ID Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 1 5.1 3.5 1.4 0.2 setosa
## 2 2 4.9 3.0 1.4 0.2 setosa
## 3 3 4.7 3.2 1.3 0.2 setosa
## 4 4 4.6 3.1 1.5 0.2 setosa
## 5 5 5.0 3.6 1.4 0.2 setosa
## 6 6 5.4 3.9 1.7 0.4 setosa
tidyr::gather 関数
gather
関数はデータフレームにを折りたたむときに使う。例えば、雌しべおよび雄しべの長さと幅を attribute として、その値を value として折りたたむときは、次のように行う。
iris.df <- iris %>% gather(`Sepal.Length`, `Sepal.Width`, `Petal.Length`, `Petal.Width`,
key = 'attribute', value = 'length')
head(iris.df)
## ID Species attribute length
## 1 1 setosa Sepal.Length 5.1
## 2 2 setosa Sepal.Length 4.9
## 3 3 setosa Sepal.Length 4.7
## 4 4 setosa Sepal.Length 4.6
## 5 5 setosa Sepal.Length 5.0
## 6 6 setosa Sepal.Length 5.4
tidyr::spread 関数
折りたたまれたデータフレームを、特定の列に基づいて展開したいときは spread
関数を使用する。
iris.spreaded <- iris.df %>% spread(key = 'attribute', value = 'length')
head(iris.spreaded)
## ID Species Petal.Length Petal.Width Sepal.Length Sepal.Width
## 1 1 setosa 1.4 0.2 5.1 3.5
## 2 2 setosa 1.4 0.2 4.9 3.0
## 3 3 setosa 1.3 0.2 4.7 3.2
## 4 4 setosa 1.5 0.2 4.6 3.1
## 5 5 setosa 1.4 0.2 5.0 3.6
## 6 6 setosa 1.7 0.4 5.4 3.9