まずは蝋の翼から。

学んだことを書きながら確認・整理するためのメモブログ。こういうことなのかな?といったことをふわっと書いたりしていますが、理解が浅いゆえに的はずれなことも多々あると思うのでツッコミ歓迎

Rの並び替えをfactorのlevelsで制御する

概要

問題

Rで列の並び順を固定したい

解決方法

factorを用いてfactor型に変換し、その際にlevelを指定する。

実践

データを読み込む

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')

# 縦持ち
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 590 more rows

このままspeciesで並び替えをすると、デフォルトではアルファベット順のため setosaversicolorvirginicav となる。

longer_iris %>% 
  select(species) %>% 
  unique() %>% 
  arrange(species)

## A tibble: 3 x 1
# species   
# <fct>     
# 1 setosa    
# 2 versicolor
# 3 virginica 

これを、
setosaversicolorvirginicav ではなく
versicolorsetosavirginicav に並び替えるために、その順番となる変数を作成する。

species_arrange = c('versicolor', 'setosa', 'virginica')

この変数を factor 型変換時にlevelを決める levels オプションに指定する。
以下ではわかりやすいように species はそのままに、levels指定をした species2を作成する。

longer_iris %>%  
  mutate(species2 = factor(species, levels = species_arrange)) %>%
  select(species, species2) %>% 
  unique() %>% 
  arrange(species2)

# species    species2  
# <fct>      <fct>     
# 1 versicolor versicolor
# 2 setosa     setosa    
# 3 virginica  virginica 

おまけ

factor指定時にlabelsで表示名の変更もできる。

species_arrange_labels = c('バージカラー', 'セトサ', 'バージニカ')

# typeの昇順(アルファベット:petal_length→...)
longer_iris %>%  
  mutate(species2 = factor(species, levels = species_arrange, labels = species_arrange_labels)) %>% 
  select(species, species2) %>% 
  unique() %>% 
  arrange(species2)

# species    species2    
# <fct>      <fct>       
# 1 versicolor バージカラー
# 2 setosa     セトサ      
# 3 virginica  バージニカ