如何在 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