ตอบ: จะตรวจสอบได้อย่างไรว่าหลายคอลัมน์เท่ากัน
คุณสามารถใช้วิธีการต่อไปนี้เพื่อตรวจสอบว่าหลายคอลัมน์เท่ากันในกรอบข้อมูลใน R หรือไม่:
วิธีที่ 1: ตรวจสอบว่าคอลัมน์ทั้งหมดเท่ากันหรือไม่
library (dplyr) #create new column that checks if all columns are equal df <- df %>% rowwise %>% mutate(match = n_distinct(unlist(cur_data())) == 1 ) %>% A group()
วิธีที่ 2: ตรวจสอบว่าคอลัมน์ที่ระบุเท่ากันหรือไม่
library (dplyr) #create new column that checks if columns 'A', 'C', and 'D' are equal df_temp <- df %>% select(' A ', ' C ', ' D ') %>% rowwise %>% mutate(match = n_distinct(unlist(cur_data())) == 1 ) %>% A group() #add new column to existing data frame df$match <- df_temp$match
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติกับกรอบข้อมูลต่อไปนี้:
#create data frame df = data. frame (A=c(4, 0, 3, 3, 6, 8, 7), B=c(4, 2, 3, 5, 6, 4, 7), C=c(4, 0, 3, 3, 5, 10, 7), D=c(4, 0, 3, 3, 3, 8, 7)) #view data frame df ABCD 1 4 4 4 4 2 0 2 0 0 3 3 3 3 3 4 3 5 3 3 5 6 6 5 3 6 8 4 10 8 7 7 7 7 7
ตัวอย่างที่ 1: ตรวจสอบ ว่าคอลัมน์ทั้งหมดเท่ากันหรือไม่
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อตรวจสอบว่าค่าของแต่ละคอลัมน์ใน data frame เท่ากันสำหรับแต่ละแถวหรือไม่:
library (dplyr) #create new column that checks if all columns are equal df <- df %>% rowwise %>% mutate(match = n_distinct(unlist(cur_data())) == 1 ) %>% A group() #view updated data frame df # A tibble: 7 x 5 ABCD match 1 4 4 4 4 TRUE 2 0 2 0 0 FALSE 3 3 3 3 3 TRUE 4 3 5 3 3 FALSE 5 6 6 5 3 FALSE 6 8 4 10 8 FALSE 7 7 7 7 7 TRUE
หากค่าของแต่ละคอลัมน์เท่ากัน คอลัมน์ ที่ตรงกัน จะส่งกลับ True
มิฉะนั้นจะส่งกลับ False
โปรดทราบว่าคุณสามารถแปลงค่า True และ False เป็น 1 และ 0 ได้โดยใช้ as.numeric() ดังนี้
library (dplyr) #create new column that checks if all columns are equal df <- df %>% rowwise %>% mutate(match = as. numeric (n_distinct(unlist(cur_data())) == 1 )) %>% A group() #view updated data frame df # A tibble: 7 x 5 ABCD match 1 4 4 4 4 1 2 0 2 0 0 0 3 3 3 3 3 1 4 3 5 3 3 0 5 6 6 5 3 0 6 8 4 10 8 0 7 7 7 7 7 1
ตัวอย่างที่ 2: ตรวจสอบว่าคอลัมน์ใดคอลัมน์หนึ่งเท่ากัน
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อตรวจสอบว่าค่าในคอลัมน์ A, C และ D ของกรอบข้อมูลเท่ากันสำหรับแต่ละแถวหรือไม่:
library (dplyr) #create new column that checks if columns 'A', 'C', and 'D' are equal df_temp <- df %>% select(' A ', ' C ', ' D ') %>% rowwise %>% mutate(match = n_distinct(unlist(cur_data())) == 1 ) %>% A group() #add new column to existing data frame df$match <- df_temp$match #view updated data frame df ABCD match 1 4 4 4 4 TRUE 2 0 2 0 0 TRUE 3 3 3 3 3 TRUE 4 3 5 3 3 TRUE 5 6 6 5 3 FALSE 6 8 4 10 8 FALSE 7 7 7 7 7 TRUE
หากค่าในคอลัมน์ A, C และ D เท่ากัน คอลัมน์ ที่ตรงกัน จะส่งกลับ True
มิฉะนั้นจะส่งกลับ False
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการงานทั่วไปอื่นๆ ใน R:
วิธีจัดเรียงตามหลายคอลัมน์ใน R
วิธีรักษาบางคอลัมน์ใน R
วิธีนับจำนวนครั้งที่เกิดขึ้นในคอลัมน์ใน R