我想删除所有超过 50% 的列或行NA
s 在数据框中。
这是我的解决方案:
# 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
解决方案
要删除具有一定数量 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)]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)