第5章 tidyverse(dplyr)で再現 ・ ノック 76 / 100 ・ [[000 - はじめに(使い方と目次)|目次]]<br>
← 前 [[075 - 一つの列をベクトルで取り出す]] ・ 次 → [[077 - 条件で値を振り分ける]]
> [!info] relocate() は列の位置を移動する動詞です
> **`relocate()`**(リロケート)は、列の順序を変える動詞です。列を削除したり名前を変えたりせず、表示される順番だけを変えます。`relocate(iris, Species)` と書くと、`Species` 列が一番左(先頭)に移動します。`.before` や `.after` 引数で「どの列の前後に移動するか」を細かく指定することもできます。
>
> Rベースでは `iris[, c("Species", "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")]` のように全列名を並べ直す必要がありましたが、`relocate()` では動かしたい列だけを指定するだけで済みます。
## 問題
`iris` の `Species` 列を先頭に移動し、先頭3行を表示してみましょう。
> [!tip] ヒント
> `relocate(データフレーム, 移動させたい列名)` と書くと、その列が一番左に移動します。
> [!success]- 回答を見る
> ```r
> library(dplyr)
> relocate(iris, Species) |> head(3)
> ```
> ```
> Species Sepal.Length Sepal.Width Petal.Length Petal.Width
> 1 setosa 5.1 3.5 1.4 0.2
> 2 setosa 4.9 3.0 1.4 0.2
> 3 setosa 4.7 3.2 1.3 0.2
> ```
> Rベースでは全列名を書き並べて順番を変えていましたが、`relocate()` を使うと「動かしたい列」だけを指定するだけで済みます。