首页 文章

删除缺少x%的列/行

提问于
浏览
14

我想删除数据框中超过50% NA 的所有列或行 .

这是我的解决方案:

# delete columns with more than 50% missings
miss <- c()
for(i in 1:ncol(data)) {
  if(length(which(is.na(data[,i]))) > 0.5*nrow(data)) miss <- append(miss,i) 
}
data2 <- data[,-miss]


# delete rows with more than 50% percent missing
miss2 <- c()
for(i in 1:nrow(data)) {
  if(length(which(is.na(data[i,]))) > 0.5*ncol(data)) miss2 <- append(miss2,i) 
}
data <- data[-miss,]

但我正在寻找一个更好/更快的解决方案 .

我也很感激 dplyr 解决方案

1 回答

  • 26

    要删除具有一定数量NA的列,您可以使用 colMeans(is.na(...))

    ## Some sample data
    set.seed(0)
    dat <- matrix(1:100, 10, 10)
    dat[sample(1:100, 50)] <- NA
    dat <- data.frame(dat)
    
    ## Remove columns with more than 50% NA
    dat[, -which(colMeans(is.na(dat)) > 0.5)]
    

    对于行类似,使用 rowMeans .

相关问题