LoginSignup
2
0

More than 1 year has passed since last update.

tidyverseでselect()とeverything()を使って任意の列を最後尾に並べ替えたい

Last updated at Posted at 2022-06-17

TL;DR

これを実行するとSepal.Length列が一番後ろ(右)にくる

d %>%
  select(-Sepal.Length, Sepal.Length) %>%
  head(1)

select()関数を使った並べ替え

tidyverseを使ってると、見栄え的な問題で列を並べ替えたくなったりする。
別にどうでもいいけどどうでもよくない、牛丼の真ん中に生卵を綺麗に落とせるかくらいどうでもよくない。
そんなとき、tidyverseのselect()関数を使うと色々便利で、特にeverything()と組み合わせると最強になれる(参考)。
例えば、こんな感じ。とりあえずirisデータセットを読み込む。

# とりあえず読み込んで中身を覗く
library(datasets)
d <- iris
head(d)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

ここで、Species列を前に持ってきたいとする。select()関数の中に、並べ替えたい順に列名を入れる。

d %>%
  select(Species, Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>%
  head(1)
#   Species Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1  setosa          5.1         3.5          1.4         0.2

でも、これで列数が増えるとめんどくさい。その時にはeverything()が使える。

d %>%
  select(Species, everything()) %>%
  head(1)
#   Species Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1  setosa          5.1         3.5          1.4         0.2

everything()の関数便利すぎだろ!

everything()が使えないとき

マジクソ鬼便利なeverything()だが、select()の末尾にしか使えない。
下の例は上手くいかない。

d %>%
  select(everything(), Sepal.Length) %>%
  head(1)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa

多分、everything()関数でSepal.Lengthがすでに呼び出されているため、二個目が無効になってるんだと思う。

なら、select(-hoge)を使って一旦目的の列をはじいてしまえばいいのでは。

d %>%
  select(-Sepal.Length, Sepal.Length) %>%
  head(1)
#   Sepal.Width Petal.Length Petal.Width Species Sepal.Length
# 1         3.5          1.4         0.2  setosa          5.1

上手くいった!
一度select(-hoge)ではじいても、同じ関数内なら再度呼び出せるらしい。

まとめ

多分これで列の並べ替えは変幻自在なはず。

追記

これでもいけるっぽい。こっちの方が分かり易いかも。

select(Sepal.Width:Species, Sepal.Length)
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0