美文网首页
R语言 -- 删除 dataFrame/matrix 中含有NA

R语言 -- 删除 dataFrame/matrix 中含有NA

作者: 生信摆渡 | 来源:发表于2020-10-12 17:00 被阅读0次

删除含有NA的行或列很简单:

na.omit()

删除全为NA的行或列貌似没有内置的函数,不过实现也很简单,按行删按列删都可以:

# 先写成函数的形式,方便调用
removeRowsAllNa  <- function(x){x[apply(x, 1, function(y) any(!is.na(y))),]}
removeColsAllNa  <- function(x){x[, apply(x, 2, function(y) any(!is.na(y)))]}

# 非函数形式则更简短,其中 x 为 DataFrame 或 Matrix 
x_RowsAllNa_removed =  x[apply(x, 1, function(y) any(!is.na(y))),]
x_ColsAllNa_removed =  x[, apply(x, 1, function(y) any(!is.na(y)))]

测试一下

a = data.frame("col1" = c(1, NA, 4), "col2" = c(2, NA, 5), "col3" = c(NA ,NA ,6))
na.omit(student)
> a
  col1 col2 col3
1    1    2   NA
2   NA   NA   NA
3    4    5   NA

> na.omit(a)
[1] col1 col2 col3
<0 rows> (or 0-length row.names)

> removeRowsAllNa(a)
  col1 col2 col3
1    1    2   NA
3    4    5   NA

> removeColsAllNa(a)
  col1 col2
1    1    2
2   NA   NA
3    4    5

非常的方便~

相关文章

网友评论

      本文标题:R语言 -- 删除 dataFrame/matrix 中含有NA

      本文链接:https://www.haomeiwen.com/subject/jwqppktx.html