วิธีเปลี่ยนชื่อคอลัมน์เดียวใน r (พร้อมตัวอย่าง)


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

วิธีที่ 1: เปลี่ยนชื่อคอลัมน์เดียวโดยใช้ Base R

 #rename column by name
colnames(df)[colnames(df) == ' old_name '] <- ' new_name '

#rename column by position
#colnames(df)[ 2 ] <- ' new_name '

วิธีที่ 2: เปลี่ยนชื่อคอลัมน์เดียวโดยใช้ dplyr

 library (dplyr)

#rename column by name
df <- df %>% rename_at(' old_name ', ~' new_name ')

#rename column by position
df <- df %>% rename_at( 2 , ~' new_name ')

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

 #create data frame
df <- data. frame (team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))

#view data frame
df

  team points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

ตัวอย่างที่ 1: เปลี่ยนชื่อคอลัมน์เดียวโดยใช้ Base R

รหัสต่อไปนี้แสดงวิธีการเปลี่ยนชื่อคอลัมน์ คะแนน เป็น Total_points โดยใช้ชื่อคอลัมน์:

 #rename 'points' column to 'total_points'
colnames(df)[colnames(df) == ' points '] <- ' total_points '

#view updated data frame
df

  team total_points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

รหัสต่อไปนี้แสดงวิธีการเปลี่ยนชื่อคอลัมน์ คะแนน เป็น Total_points โดยใช้ตำแหน่งคอลัมน์:

 #rename column in position 2 to 'total_points'
colnames(df)[ 2 ] <- ' total_points '

#view updated data frame
df

  team total_points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

โปรดทราบว่าทั้งสองวิธีให้ผลลัพธ์ที่เหมือนกัน

ตัวอย่างที่ 2: เปลี่ยนชื่อคอลัมน์เดียวโดยใช้ dplyr

รหัสต่อไปนี้แสดงวิธีเปลี่ยนชื่อคอลัมน์ คะแนน เป็น Total_points ตามชื่อโดยใช้ฟังก์ชัน rename_at() ใน dplyr :

 library (dplyr)

#rename 'points' column to 'total_points' by name
df <- df %>% rename_at(' points ', ~' total_points ')

#view updated data frame
df

  team total_points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

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

 library (dplyr)

#rename column in position 2 to 'total_points'
df <- df %>% rename_at( 2 , ~' total_points ')

#view updated data frame
df

  team total_points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

โปรดทราบว่าทั้งสองวิธีให้ผลลัพธ์ที่เหมือนกัน

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

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

วิธีเลือกคอลัมน์เฉพาะใน R
วิธีรักษาบางคอลัมน์ใน R
วิธีจัดเรียงตามหลายคอลัมน์ใน R

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

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