删除超过 x% 的 columns/rows

Delete columns/rows with more than x% missing

我想删除数据框中超过 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,]

但我正在寻找 nicer/faster 解决方案。

我也很感激 dplyr 解决方案

要删除具有一定量 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)]

## Remove rows with more than 50% NA
dat[which(rowMeans(!is.na(dat)) > 0.5), ]

## Remove columns and rows with more than 50% NA
dat[which(rowMeans(!is.na(dat)) > 0.5), which(colMeans(!is.na(dat)) > 0.5)]

一个 tidyverse 解决方案,在此处删除 x% 为 NAs(50%) 的列:

test_data <- data.frame(A=c(rep(NA,12),
                            520,233,522),
                        B = c(rep(10,12),
                              520,233,522))
# Remove all with %NA >= 50
# can just use >50


 test_data %>% 
  purrr::discard(~sum(is.na(.x))/length(.x)* 100 >=50)

结果:

     B
1   10
2   10
3   10
4   10
5   10
6   10
7   10
8   10
9   10
10  10
11  10
12  10
13 520
14 233
15 522

这是另一个提示 ro 过滤器 df,它在列中有 50 个 NaN:

## Remove columns with more than 50% NA
rawdf.prep1 = rawdf[, sapply(rawdf, function(x) sum(is.na(x)))/nrow(rawdf)*100 <= 50]

这将导致一个 df 在不大于 50% 的列中只有 NaN。

一个 dplyr 解决方案

对于select基于逻辑条件的列,我们可以使用选择助手where(),如:

library(dplyr)

threshold<-0.5 #for a 50% cut-off

df %>% select(where(~mean(is.na(.))< threshold))

对于 filtering 行,dplyrs if_any()if_all() 将处理 100 或 0% 截止值的情况,如 df %>% filter(if_any(everything(), ~is.na(.x))) 中那样。 对于具有其他阈值的解决方案,您可以使用 rowMeans:

library(dplyr)

df %>% filter(rowMeans(is.na(.)) < threshold)