省略包含特定列的 NA 的行 [英] Omit rows containing specific column of NA

查看:20
本文介绍了省略包含特定列的 NA 的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在数据框中省略 NA 值,但仅限于我感兴趣的某些列.

I want to know how to omit NA values in a data frame, but only in some columns I am interested in.

例如

DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))

但我只想省略yNA的数据,因此结果应该是

but I only want to omit the data where y is NA, therefore the result should be

  x  y  z
1 1  0 NA
2 2 10 33

na.omit 似乎删除所有包含任何 NA 的行.

na.omit seems delete all rows contain any NA.

有人能帮我解决这个简单的问题吗?

Can somebody help me out of this simple question?

但如果现在我改变问题,如:

But if now I change the question like:

DF <- data.frame(x = c(1, 2, 3,NA), y = c(1,0, 10, NA), z=c(43,NA, 33, NA))

如果我只想省略x=naz=na,我可以把| 放在函数的什么地方?

If I want to omit only x=na or z=na, where can I put the | in function?

推荐答案

你可以使用 complete.cases 函数,这样把它放到一个函数中:

You could use the complete.cases function and put it into a function thusly:

DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))

completeFun <- function(data, desiredCols) {
  completeVec <- complete.cases(data[, desiredCols])
  return(data[completeVec, ])
}

completeFun(DF, "y")
#   x  y  z
# 1 1  0 NA
# 2 2 10 33

completeFun(DF, c("y", "z"))
#   x  y  z
# 2 2 10 33

只返回没有NAs

如果您想消除任何列中至少有一个 NA 的所有行,只需直接使用 complete.cases 函数:

If you want to eliminate all rows with at least one NA in any column, just use the complete.cases function straight up:

DF[complete.cases(DF), ]
#   x  y  z
# 2 2 10 33

或者如果 completeFun 已经在您的工作流程中根深蒂固;)

Or if completeFun is already ingrained in your workflow ;)

completeFun(DF, names(DF))

这篇关于省略包含特定列的 NA 的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆