R에서 행을 삭제하는 방법(예제 포함)
다음 구문을 사용하여 R에서 특정 줄 번호를 제거할 수 있습니다.
#remove 4th row new_df <- df[-c(4), ] #remove 2nd through 4th row new_df <- df[-c(2:4), ] #remove 1st, 2nd, and 4th row new_df <- df[-c(1, 2, 4), ]
다음 구문을 사용하여 특정 조건을 충족하지 않는 행을 제거할 수 있습니다.
#only keep rows where col1 value is less than 10 and col2 value is less than 6 new_df <- subset(df, col1 < 10 & col2 < 6)
그리고 다음 구문을 사용하여 모든 열에서 NA 값이 있는 행을 제거할 수 있습니다.
#remove rows with NA value in any column new_df <- na. omitted (df)
다음 예에서는 이러한 각 기능을 실제로 사용하는 방법을 보여줍니다.
예시 1: 숫자별로 행 삭제
다음 코드는 R에서 특정 행 번호로 행을 삭제하는 방법을 보여줍니다.
#create data frame df <- data. frame (player=c('A', 'B', 'C', 'D', 'E'), pts=c(17, 12, 8, 9, 25), rebs=c(3, 3, 6, 5, 8), blocks=c(1, 1, 2, 4, NA)) #view data frame df player pts rebs blocks 1 to 17 3 1 2 B 12 3 1 3 C 8 6 2 4 D 9 5 4 5 E 25 8 NA #remove 4th row df[-c(4), ] player pts rebs blocks 1 to 17 3 1 2 B 12 3 1 3 C 8 6 2 5 E 25 8 NA #remove 2nd through 4th row df[-c(2:4), ] player pts rebs blocks 1 to 17 3 1 5 E 25 8 NA #remove 1st, 2nd, and 4th row df[-c(1, 2, 4), ] player pts rebs blocks 3 C 8 6 2 5 E 25 8 NA
예시 2: 조건에 따라 행 삭제
다음 코드는 특정 조건을 충족하지 않는 행을 제거하는 방법을 보여줍니다.
#create data frame df <- data. frame (player=c('A', 'B', 'C', 'D', 'E'), pts=c(17, 12, 8, 9, 25), rebs=c(3, 3, 6, 5, 8), blocks=c(1, 1, 2, 4, NA)) #view data frame df player pts rebs blocks 1 to 17 3 1 2 B 12 3 1 3 C 8 6 2 4 D 9 5 4 5 E 25 8 NA #only keep rows where pts is less than 10 and rebs is less than 6 subset(df, pts < 10 & rebs < 6) player pts rebs blocks 4 D 9 5 4
예시 3: NA 값이 있는 행 삭제
다음 코드는 행에서 NA 값이 있는 행을 제거하는 방법을 보여줍니다.
#create data frame df <- data. frame (player=c('A', 'B', 'C', 'D', 'E'), pts=c(17, 12, 8, 9, 25), rebs=c(3, 3, 6, 5, 8), blocks=c(1, 1, 2, 4, NA)) #view data frame df player pts rebs blocks 1 to 17 3 1 2 B 12 3 1 3 C 8 6 2 4 D 9 5 4 5 E 25 8 NA #remove rows with NA value in any row: n / A. omitted (df) player pts rebs blocks 1 to 17 3 1 2 B 12 3 1 3 C 8 6 2 4 D 9 5 4