查找所有缺少值的列 [英] Find columns with all missing values

查看:85
本文介绍了查找所有缺少值的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数,它需要检查(和哪个!)列(变量)都缺少值( NA < NA> )。以下是函数的片段:

  test1<  -  data.frame(matrix(c(1,2,3, (c,1,2,3,NA,NA,NA,2,3,3))
test2< - data.frame 2),3,3))

na.test< - function(data){
if(colSums(!is.na(data)== 0)){
stop(数据集中的一些变量都缺少值,
删除列以继续)
}
}
na.test(test1)

警告信息:
如果(colSums(!is.na(data)== 0)){:
条件具有长度> 1,只有第一个元素将被使用

Q1:为什么以上错误和任何修复?



Q2:有没有办法找到哪些列全部为 NA ,例如输出列表(变量或列号的名称)?

解决方案

这很容易与 sapply 和一个小的匿名函数:

  sapply(test1,function (x)all(is.na(x)))
X1 X2 X3
FALSE FALSE FALSE

sapply(test2,function(x)all(is.na )))
X1 X2 X3
FALSE TRUE FALSE






在函数内:

  na.test<  -  function(x){
w< - sapply(x,function(x)all(is.na(x)))
if(any(w)){
停止(粘贴(列中的所有NA (其中(w),collapse =,)))
}
}

na.test(test1)

na.test test2)
na.test(test2)中的错误:列2中的所有NA


I am writing a function, which needs a check on whether (and which!) column (variable) has all missing values (NA, <NA>). The following is fragment of the function:

test1 <- data.frame (matrix(c(1,2,3,NA,2,3,NA,NA,2), 3,3))
test2 <- data.frame (matrix(c(1,2,3,NA,NA,NA,NA,NA,2), 3,3))

na.test <-  function (data) {
  if (colSums(!is.na(data) == 0)){
      stop ("The some variable in the dataset has all missing value,
     remove the column to proceed")
      }
      }
na.test (test1)

Warning message:
In if (colSums(!is.na(data) == 0)) { :
  the condition has length > 1 and only the first element will be used

Q1: Why is the above error and any fixes ?

Q2: Is there any way to find which of columns have all NA, for example output the list (name of variable or column number)?

解决方案

This is easy enough to with sapply and a small anonymous function:

sapply(test1, function(x)all(is.na(x)))
   X1    X2    X3 
FALSE FALSE FALSE 

sapply(test2, function(x)all(is.na(x)))
   X1    X2    X3 
FALSE  TRUE FALSE 


And inside a function:

na.test <-  function (x) {
  w <- sapply(x, function(x)all(is.na(x)))
  if (any(w)) {
    stop(paste("All NA in columns", paste(which(w), collapse=", ")))
  }
}

na.test(test1)

na.test(test2)
Error in na.test(test2) : All NA in columns 2

这篇关于查找所有缺少值的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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