Skip to main content

列の移動

準備

1. パッケージのインストール

install.packages("tidyverse")

2. パッケージの読み込み

library(tidyverse)

プログラム

RPythonSQL
1. 最初の位置に移動AwesomeNot AwesomeAwesome
2. 最後の位置に移動AwesomeNot AwesomeAwesome
3. 指定した列の前後の位置に移動AwesomeNot Awesome-

1. 最初の位置に移動

構文
df %>%
relocate(col1, col2)
サンプルコード
penguins %>%
relocate(bill_length_mm, bill_depth_mm)

# # A tibble: 344 × 7
# bill_length_mm bill_depth_mm species island flipper_length_mm body_mass_g sex
# <dbl> <dbl> <fct> <fct> <int> <int> <fct>
# 1 39.1 18.7 Adelie Torgersen 181 3750 male
# 2 39.5 17.4 Adelie Torgersen 186 3800 female
# 3 40.3 18 Adelie Torgersen 195 3250 female
# 4 NA NA Adelie Torgersen NA NA NA
# 5 36.7 19.3 Adelie Torgersen 193 3450 female
# 6 39.3 20.6 Adelie Torgersen 190 3650 male
# 7 38.9 17.8 Adelie Torgersen 181 3625 female
# 8 39.2 19.6 Adelie Torgersen 195 4675 male
# 9 34.1 18.1 Adelie Torgersen 193 3475 NA
# 10 42 20.2 Adelie Torgersen 190 4250 NA
# # ℹ 334 more rows
# # ℹ Use `print(n = ...)` to see more rows

2. 最後の位置に移動

構文
df %>%
relocate(col1, col2, .after = last_col())
サンプルコード
penguins %>%
relocate(bill_length_mm, bill_depth_mm, .after = last_col())

# # A tibble: 344 × 7
# species island flipper_length_mm body_mass_g sex bill_length_mm bill_depth_mm
# <fct> <fct> <int> <int> <fct> <dbl> <dbl>
# 1 Adelie Torgersen 181 3750 male 39.1 18.7
# 2 Adelie Torgersen 186 3800 female 39.5 17.4
# 3 Adelie Torgersen 195 3250 female 40.3 18
# 4 Adelie Torgersen NA NA NA NA NA
# 5 Adelie Torgersen 193 3450 female 36.7 19.3
# 6 Adelie Torgersen 190 3650 male 39.3 20.6
# 7 Adelie Torgersen 181 3625 female 38.9 17.8
# 8 Adelie Torgersen 195 4675 male 39.2 19.6
# 9 Adelie Torgersen 193 3475 NA 34.1 18.1
# 10 Adelie Torgersen 190 4250 NA 42 20.2
# # ℹ 334 more rows
# # ℹ Use `print(n = ...)` to see more rows

3. 指定した列の前後の位置に移動

構文
df %>%
relocate(col1, col2, .before = col3) # または .after = col3
サンプルコード
penguins %>%
relocate(bill_length_mm, bill_depth_mm, .before = island)

# # A tibble: 344 × 7
# species bill_length_mm bill_depth_mm island flipper_length_mm body_mass_g sex
# <fct> <dbl> <dbl> <fct> <int> <int> <fct>
# 1 Adelie 39.1 18.7 Torgersen 181 3750 male
# 2 Adelie 39.5 17.4 Torgersen 186 3800 female
# 3 Adelie 40.3 18 Torgersen 195 3250 female
# 4 Adelie NA NA Torgersen NA NA NA
# 5 Adelie 36.7 19.3 Torgersen 193 3450 female
# 6 Adelie 39.3 20.6 Torgersen 190 3650 male
# 7 Adelie 38.9 17.8 Torgersen 181 3625 female
# 8 Adelie 39.2 19.6 Torgersen 195 4675 male
# 9 Adelie 34.1 18.1 Torgersen 193 3475 NA
# 10 Adelie 42 20.2 Torgersen 190 4250 NA
# # ℹ 334 more rows
# # ℹ Use `print(n = ...)` to see more rows