วิธีใช้ฟังก์ชัน relocate() ใน dplyr (พร้อมตัวอย่าง)


คุณสามารถใช้ฟังก์ชัน relocate() จากแพ็คเกจ dplyr ใน R เพื่อเปลี่ยนตำแหน่งคอลัมน์ในกรอบข้อมูล

คุณสามารถใช้วิธีการต่อไปนี้เพื่อเปลี่ยนตำแหน่งคอลัมน์:

วิธีที่ 1: ย้ายคอลัมน์ไปข้างหน้า

 #move 'x' column to front
df %>% relocate(x)

วิธีที่ 2: ย้ายหลายคอลัมน์ไปข้างหน้า

 #move 'x' and 'y' columns to front
df %>% relocate(x, y)

วิธีที่ 3: ย้ายคอลัมน์ไปยังตำแหน่งหลังคอลัมน์อื่น

 #move 'x' column to position after 'y' column
df %>% relocate(x, . after =y)

วิธีที่ 4: ย้ายคอลัมน์ไปยังตำแหน่งก่อนคอลัมน์อื่น

 #move 'x' column to position before 'y' column
df %>% relocate(x, . before =y)

ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีกับกรอบข้อมูลต่อไปนี้:

 #create dataset
df <- data. frame (team=c('A', 'A', 'A', 'B', 'B', 'C', 'C'),
                 points=c(1, 2, 3, 4, 5, 6, 7),
                 assists=c(1, 5, 2, 3, 2, 2, 0),
                 rebounds=c(6, 6, 10, 12, 8, 8, 3))

#view dataset
df

  team points assists rebounds
1 A 1 1 6
2 A 2 5 6
3 A 3 2 10
4 B 4 3 12
5 B 5 2 8
6 C 6 2 8
7 C 7 0 3

ตัวอย่างที่ 1: ย้ายคอลัมน์ไปข้างหน้า

รหัสต่อไปนี้แสดงวิธีการใช้ฟังก์ชัน relocate() เพื่อย้ายคอลัมน์ไปข้างหน้า:

 #move 'assists' column to front
df %>% relocate(assists)

  assists team points rebounds
1 1 To 1 6
2 5 A 2 6
3 2 A 3 10
4 3 B 4 12
5 2 B 5 8
6 2 C 6 8
7 0 C 7 3

ตัวอย่างที่ 2: ย้ายหลายคอลัมน์ไปข้างหน้า

รหัสต่อไปนี้แสดงวิธีการใช้ฟังก์ชัน relocate() เพื่อย้ายหลายคอลัมน์ไปข้างหน้า:

 #move 'points' and 'assists' to front
df %>% relocate(points, assists)

  points assists team rebounds
1 1 1 A 6
2 2 5 A 6
3 3 2 A 10
4 4 3 B 12
5 5 2 B 8
6 6 2 C 8
7 7 0 C 3

ตัวอย่างที่ 3: ย้ายคอลัมน์ไปยังตำแหน่งหลังคอลัมน์อื่น

รหัสต่อไปนี้แสดงวิธีการใช้ฟังก์ชัน relocate() เพื่อย้ายคอลัมน์ไปยังตำแหน่งเฉพาะผ่านคอลัมน์อื่น:

 #move 'team' column to after 'assists' column
df %>% relocate(team, . after =assists)

  points assists team rebounds
1 1 1 A 6
2 2 5 A 6
3 3 2 To 10
4 4 3 B 12
5 5 2 B 8
6 6 2 C 8
7 7 0 C 3

ตัวอย่างที่ 4: ย้ายคอลัมน์ไปยังตำแหน่งก่อนคอลัมน์อื่น

รหัสต่อไปนี้แสดงวิธีการใช้ฟังก์ชัน relocate() เพื่อย้ายคอลัมน์ไปยังตำแหน่งเฉพาะก่อนคอลัมน์อื่น:

 #move 'team' column to before 'rebounds' column
df %>% relocate(team, . before =rebounds)

  points assists team rebounds
1 1 1 A 6
2 2 5 A 6
3 3 2 To 10
4 4 3 B 12
5 5 2 B 8
6 6 2 C 8
7 7 0 C 3

แหล่งข้อมูลเพิ่มเติม

บทช่วยสอนต่อไปนี้จะอธิบายวิธีการใช้งานฟังก์ชันทั่วไปอื่นๆ โดยใช้ dplyr:

วิธีลบแถวโดยใช้ dplyr
วิธีจัดเรียงแถวโดยใช้ dplyr
วิธีกรองตามเงื่อนไขต่างๆ โดยใช้ dplyr

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *