Rで縦持ち・横持ち化する
Rでは、今まで縦持ち化するときにはtidyr::gather
、横持ち化するときはtidyr::spread
を使っていたがオプションが毎回よくわからずドキュメントを読んでいたが、それはみんな同じことを思ってたみたいでdplyr1.0以降では再設計されてtidyr::gather
→tidyr::pivot_longer
、tidyr::spread
→tidyr::pivot_wider
に変更されるとともにオプションも直感的に変わった模様。
実装
とりあえずirisを使ってデータ準備
library(tidyverse) library(tidylog) df_iris = iris %>% tibble() %>% select(species=Species, sepal_length=Sepal.Length, sepal_width=Sepal.Width, petal_length=Petal.Length, petal_width=Petal.Width) %>% rowid_to_column('id') # id species sepal_length sepal_width petal_length petal_width # <int> <fct> <dbl> <dbl> <dbl> <dbl> # 1 1 setosa 5.1 3.5 1.4 0.2 # 2 2 setosa 4.9 3 1.4 0.2 # 3 3 setosa 4.7 3.2 1.3 0.2 # 4 4 setosa 4.6 3.1 1.5 0.2 # 5 5 setosa 5 3.6 1.4 0.2 # 6 6 setosa 5.4 3.9 1.7 0.4 # 7 7 setosa 4.6 3.4 1.4 0.3 # 8 8 setosa 5 3.4 1.5 0.2 # 9 9 setosa 4.4 2.9 1.4 0.2 # 10 10 setosa 4.9 3.1 1.5 0.1 # # … with 140 more rows
縦持ち化。
オプションのcols
で縦持ちにするときの対象となる列を指定。- で除外していも可能。
# 縦持ち longer_iris = df_iris %>% pivot_longer(cols = c(-id,-species), # 縦持ち対象にしたい列 names_to = 'type', # 縦持ち化の列名 # デフォルトだと'name' values_to = 'values') # 値が入る列名 # デフォルトだと'value' # A tibble: 600 x 4 # id species type values # <int> <fct> <chr> <dbl> # 1 1 setosa sepal_length 5.1 # 2 1 setosa sepal_width 3.5 # 3 1 setosa petal_length 1.4 # 4 1 setosa petal_width 0.2 # 5 2 setosa sepal_length 4.9 # 6 2 setosa sepal_width 3 # 7 2 setosa petal_length 1.4 # 8 2 setosa petal_width 0.2 # 9 3 setosa sepal_length 4.7 # 10 3 setosa sepal_width 3.2 # # … with 140 more rows
横持ち化
names_fromで横持ち列名の対象を指定、values_fromで各横持ち列の値を指定。
# 横持ち longer_iris %>% pivot_wider(names_from = type, # 横持ち列名の対象 values_from = values) # 各横持ち列の値 # # A tibble: 150 x 6 # id species sepal_length sepal_width petal_length petal_width # <int> <fct> <dbl> <dbl> <dbl> <dbl> # 1 1 setosa 5.1 3.5 1.4 0.2 # 2 2 setosa 4.9 3 1.4 0.2 # 3 3 setosa 4.7 3.2 1.3 0.2 # 4 4 setosa 4.6 3.1 1.5 0.2 # 5 5 setosa 5 3.6 1.4 0.2 # 6 6 setosa 5.4 3.9 1.7 0.4 # 7 7 setosa 4.6 3.4 1.4 0.3 # 8 8 setosa 5 3.4 1.5 0.2 # 9 9 setosa 4.4 2.9 1.4 0.2 # 10 10 setosa 4.9 3.1 1.5 0.1 # # … with 140 more rows