A: 여러 열이 동일한지 확인하는 방법
다음 방법을 사용하여 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: 모든 열이 동일한지 확인
다음 구문을 사용하여 데이터 프레임의 각 열 값이 각 행에 대해 동일한지 확인할 수 있습니다.
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 를 반환합니다.
다음과 같이 as.numeric()을 사용하여 True 및 False 값을 1 과 0 으로 변환할 수 있다는 점에 유의하세요.
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의 열에서 발생 횟수를 계산하는 방법