R에서 일부 또는 전체 na가 있는 행을 삭제하는 방법
R의 데이터 프레임에서 NA(결측값)의 일부 또는 전부를 포함하는 행을 제거하려는 경우가 종종 있습니다.
이 튜토리얼에서는 Basic R 및 Tidyr 패키지를 사용하여 이러한 줄을 제거하는 방법을 설명합니다. 다음 각 예에 대해 다음 데이터 프레임을 사용합니다.
#create data frame with some missing values df <- data.frame(points = c(12, NA, 19, 22, 32), assists = c(4, NA, 3, NA, 5), rebounds = c(5, NA, 7, 12, NA)) #view data frame df points assists rebounds 1 12 4 5 2 NA NA NA 3 19 3 7 4 22 NA 12 5 32 5 NA
Base R을 사용하여 NA 제거
다음 코드는 Complete.cases()를 사용하여 열에 누락된 값이 있는 데이터 프레임의 모든 행을 제거하는 방법을 보여줍니다.
#remove all rows with a missing value in any column df[ complete.cases (df),] points assists rebounds 1 12 4 5 3 19 3 7
다음 코드는 Complete.cases()를 사용하여 특정 열에 누락된 값이 있는 데이터 프레임의 모든 행을 제거하는 방법을 보여줍니다.
#remove all rows with a missing value in the third column df[ complete.cases (df[,3]),] points assists rebounds 1 12 4 5 3 19 3 7 4 22 NA 12 #remove all rows with a missing value in either the first or third column df[ complete.cases (df[ , c(1,3)]),] points assists rebounds 1 12 4 5 3 19 3 7 4 22 NA 12
Tidyr을 사용하여 NA 삭제
다음 코드는 Tidyr 패키지의 drop_na()를 사용하여 열에 누락된 값이 있는 데이터 프레임의 모든 행을 삭제하는 방법을 보여줍니다.
#load tidyr package
library(tidyr)
#remove all rows with a missing value in any column
df %>% drop_na()
points assists rebounds
1 12 4 5
3 19 3 7
다음 코드는 Tidyr 패키지의 drop_na()를 사용하여 특정 열에 누락된 값이 있는 데이터 프레임의 모든 행을 삭제하는 방법을 보여줍니다.
#load tidyr package
library(tidyr)
#remove all rows with a missing value in the third column
df %>% drop_na(rebounds)
points assists rebounds
1 12 4 5
3 19 3 7
4 22 NA 12
여기에서 더 많은 R 튜토리얼을 찾을 수 있습니다.