R - 为 NA,NaN,DIV/0 清理数据集列
R - Cleaning dataset columns for NA,NaN,DIV/0
我有一个包含 160 列的数据集。其中一些列包含大量 NA 和 #DIV/0!
我按以下方式加载数据:
training = read.csv("training.csv",header = TRUE,na.strings = c("NA","NaN","","#DIV/0!"))
如何只保留所有行中都包含值的列?
也许:
training[ , colSums(is.na(training)) == 0]
@SRivero 的回答有效,这是另一个
set.seed(1234)
dat <- as.data.frame(matrix(runif(100000),1000,10))
dat[sample(1:100,20,replace=TRUE),sample(1:10,3,replace=TRUE)] <- NA
# apply through each column seeing if any are NAs
dat[,sapply(dat,function(x) !any(is.na(x)))]
# Check if both answers give same result
all.equal(dat[,which(sapply(dat,function(x) !any(is.na(x))))],
dat[ , colSums(is.na(dat)) == 0])
[1] TRUE
虽然我的速度有点快
library(microbenchmark)
microbenchmark(dat[,sapply(dat,function(x) !any(is.na(x)))],
dat[ , colSums(is.na(dat)) == 0])
Unit: microseconds
expr min lq mean median uq max neval
dat[, sapply(dat, function(x) !any(is.na(x)))] 87.464 89.7790 94.51491 90.9830 97.124 190.865 100
dat[, colSums(is.na(dat)) == 0] 197.958 199.9585 226.49657 201.4265 207.278 1382.612 100
使用 dplyr
中的 select_if()
的另一个选项。它允许您在数据框的列上使用谓词。仅选择谓词 returns TRUE
的那些列:
library(dplyr)
select_if(dat, function(x) !any(is.na(x))
我有一个包含 160 列的数据集。其中一些列包含大量 NA 和 #DIV/0! 我按以下方式加载数据:
training = read.csv("training.csv",header = TRUE,na.strings = c("NA","NaN","","#DIV/0!"))
如何只保留所有行中都包含值的列?
也许:
training[ , colSums(is.na(training)) == 0]
@SRivero 的回答有效,这是另一个
set.seed(1234)
dat <- as.data.frame(matrix(runif(100000),1000,10))
dat[sample(1:100,20,replace=TRUE),sample(1:10,3,replace=TRUE)] <- NA
# apply through each column seeing if any are NAs
dat[,sapply(dat,function(x) !any(is.na(x)))]
# Check if both answers give same result
all.equal(dat[,which(sapply(dat,function(x) !any(is.na(x))))],
dat[ , colSums(is.na(dat)) == 0])
[1] TRUE
虽然我的速度有点快
library(microbenchmark)
microbenchmark(dat[,sapply(dat,function(x) !any(is.na(x)))],
dat[ , colSums(is.na(dat)) == 0])
Unit: microseconds
expr min lq mean median uq max neval
dat[, sapply(dat, function(x) !any(is.na(x)))] 87.464 89.7790 94.51491 90.9830 97.124 190.865 100
dat[, colSums(is.na(dat)) == 0] 197.958 199.9585 226.49657 201.4265 207.278 1382.612 100
使用 dplyr
中的 select_if()
的另一个选项。它允许您在数据框的列上使用谓词。仅选择谓词 returns TRUE
的那些列:
library(dplyr)
select_if(dat, function(x) !any(is.na(x))