在R中只返回包含NA的列 [英] Return only columns containing NA in R

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

问题描述

我有以下数据框:

i3<-c(1,1,1,1,2,2)
i2<-c(NA,1,1,1,2,2)
i1<-c(1,NA,2,4,5,3)
newdat1<-data.frame(i3,i2,i1)
print(newdat1)
  i3 i2 i1
1  1 NA  1
2  1  1 NA
3  1  1  2
4  1  1  4
5  2  2  5
6  2  2  3

我意识到这个解决方案很简单,但是我试图返回所有NA的列,以便最终的结果如下所示:

I realize the solution for this is quite simple, but I am trying to return all the columns that any NA so that the final result looks like:

  i2 i1
1 NA  1
2  1 NA
3  1  2
4  1  4
5  2  5
6  2  3

我发现以下代码正好相反:

I have found the following code which does the opposite:

newdat1<-newdat1[, sapply(newdat1, Negate(anyNA)), drop = FALSE]

但是我找不到我正在找的东西。谢谢。

But I cannot find exactly what I am looking for. Thank you.

推荐答案

解决方案应用和子集: p>

A solution with apply and subsetting:

ind <- apply(newdat1, 2, function(x) sum(is.na(x)) == 0 )

newdat1[!ind]
  i2 i1
1 NA  1
2  1 NA
3  1  2
4  1  4
5  2  5
6  2  3

这篇关于在R中只返回包含NA的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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