R에서 중복 행을 제거하는 방법(예제 포함)
R의 데이터 프레임에서 중복 행을 제거하려면 두 가지 방법 중 하나를 사용할 수 있습니다.
방법 1: 기본 R 사용
#remove duplicate rows across entire data frame df[ ! duplicated(df), ] #remove duplicate rows across specific columns of data frame df[ ! duplicated(df[c(' var1 ')]), ]
방법 2: dplyr 사용
#remove duplicate rows across entire data frame df %>% distinct(.keep_all = TRUE ) #remove duplicate rows across specific columns of data frame df %>% distinct(var1, .keep_all = TRUE )
다음 예에서는 다음 데이터 프레임에서 실제로 이 구문을 사용하는 방법을 보여줍니다.
#define data frame df <- data. frame (team=c('A', 'A', 'A', 'B', 'B', 'B'), position=c('Guard', 'Guard', 'Forward', 'Guard', 'Center', 'Center')) #view data frame df team position 1A Guard 2 A Guard 3 A Forward 4 B Guard 5B Center 6B Center
예 1: Base R을 사용하여 중복 행 제거
다음 코드는 R 기본 함수를 사용하여 데이터 프레임에서 중복 행을 제거하는 방법을 보여줍니다.
#remove duplicate rows from data frame
df[ ! duplicated(df), ]
team position
1A Guard
3 A Forward
4 B Guard
5B Center
다음 코드는 기본 R을 사용하여 데이터 프레임의 특정 열에서 중복 행을 제거하는 방법을 보여줍니다.
#remove rows where there are duplicates in the 'team' column
df[ ! duplicated(df[c(' team ')]), ]
team position
1A Guard
4 B Guard
예 2: dplyr을 사용하여 중복 행 제거
다음 코드는 dplyr 패키지의 independent() 함수를 사용하여 데이터 프레임에서 중복 행을 제거하는 방법을 보여줍니다.
library (dplyr) #remove duplicate rows from data frame df %>% distinct(.keep_all = TRUE ) team position 1A Guard 2 A Forward 3 B Guard 4B Center
.keep_all 인수는 R에게 원본 데이터 프레임의 모든 열을 유지하도록 지시합니다.
다음 코드는 independent() 함수를 사용하여 데이터 프레임의 특정 열에서 중복 행을 제거하는 방법을 보여줍니다.
library (dplyr) #remove duplicate rows from data frame df %>% distinct(team, .keep_all = TRUE ) team position 1A Guard 2 B Guard
추가 리소스
다음 튜토리얼에서는 R에서 다른 일반적인 기능을 수행하는 방법을 설명합니다.