删除第一行之后的所有行,并删除所有 NA

  • 本文关键字:删除 NA 一行 之后 r
  • 更新时间 :
  • 英文 :


我有以下向量:

col1<-c("one", NA,"three",NA,"four","five")
col2<-c("fish", "cat","dog",NA,"deer","fox")
(df<-as.data.frame(cbind(col1,col2), stringsAsFactors = F))
   col1 col2
1   one fish
2  <NA>  cat
3 three  dog
4  <NA> <NA>
5  four deer
6  five  fox

我想删除所有具有所有Na(以及NA行本身)的第一行之后的所有行。我的预期结果:

   col1 col2
1   one fish
2  <NA>  cat
3 three  dog

使用rowSumscumsum的选项。

df[cumsum(rowSums(is.na(df)) == ncol(df)) == 0, ]
#   col1 col2
#1   one fish
#2  <NA>  cat
#3 three  dog

要了解这个单线,我们可以逐步将其分解

rowSums(is.na(df))
#[1] 0 1 0 2 0 0
rowSums(is.na(df)) == ncol(df)
#[1] FALSE FALSE FALSE  TRUE FALSE FALSE
cumsum(rowSums(is.na(df)) == ncol(df))
#[1] 0 0 0 1 1 1

现在只用0。

过滤这些行

或用which.max的其他替代方案,它将返回第一个TRUE值的索引

df[1:(which.max(rowSums(is.na(df)) == ncol(df)) - 1), ]
#   col1 col2
#1   one fish
#2  <NA>  cat
#3 three  dog

这是一个基本R选项,它可以找到具有一个或多个NA值的行的所有索引。然后,它找到了第二到最小索引的索引,并将原始数据框架子集包含所有行,但不包括,第二次至最小的NA索引。

na_index <- which(rowSums(is.na(df)) > 0)                # rows with one or more NA
keep_index <- min(na_index[na_index != min(na_index)])   # second to last NA index
df[1:(keep_index-1), ]                                   # subset data frame
   col1 col2
1   one fish
2  <NA>  cat
3 three  dog

可能是:

的基本解决方案略有不同
df[1:nrow(df) < min(which(rowSums(is.na(df[, 1:length(df)])) == length(df))), ]
   col1 col2
1   one fish
2  <NA>  cat
3 three  dog

首先,标识最小的行号,其中缺少值的数量等于变量的数量。然后,它通过仅保留在给定条件下的行号下方的行来子集数据。

或与dplyr相同的:

df %>%
 filter(row_number() < min(which(rowSums(is.na(.[, 1:length(.)])) == length(.))))

最新更新