32

列 (変数) にすべての欠損値 ( NA<NA>) があるかどうか (およびどの!) をチェックする必要がある関数を作成しています。以下は、関数のフラグメントです。

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:上記のエラーと修正方法はなぜですか?

Q2:NAリスト (変数の名前または列番号) を出力するなど、すべての列を見つける方法はありますか?

4

9 に答える 9

41

sapplyこれは、小さな無名関数を使用するだけで簡単に実行できます。

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 

そして関数内:

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
于 2012-07-04T13:40:24.343 に答える
8

dplyr で

ColNums_NotAllMissing <- function(df){ # helper function
  as.vector(which(colSums(is.na(df)) != nrow(df)))
}

df %>%
select(ColNums_NotAllMissing(.))

example:
x <- data.frame(x = c(NA, NA, NA), y = c(1, 2, NA), z = c(5, 6, 7))

x %>%
select(ColNums_NotAllMissing(.))

または、その逆

Cols_AllMissing <- function(df){ # helper function
  as.vector(which(colSums(is.na(df)) == nrow(df)))
}


x %>%
  select(-Cols_AllMissing(.))
于 2015-03-26T00:37:49.497 に答える
4

列にすべての欠損値があるかどうかをテストするには:

apply(test1,2,function(x) {all(is.na(x))})

すべての欠損値を持つ列を取得するには:

  test1.nona <- test1[ , colSums(is.na(test1)) == 0]
于 2016-06-07T01:52:27.783 に答える