10.51 Omitting Observations

20180726 An alternative is to remove observations that have missing values. Here data.table::na.omit() identifies the rows to omit based on the vars to be included for modelling. The list of rows to omit is stored as the na.action attribute of the returned object. We then remove these observations from the dataset.

Notice we keep a copy of the original dataset and then restore it.

# Backup the dataset so we can restore it as required.

ods <- ds

# Initialise the list of observations to be removed.

omit <- NULL
# Review the current dataset.

ds[vars] %>% nrow()
## [1] 172430
ds[vars] %>% is.na() %>% sum()
## [1] 399165
# Identify any observations with missing values.

mo <- attr(na.omit(ds[vars]), "na.action")

# Record the observations to omit.

omit <- union(omit, mo)

# If there are observations to omit then remove them.

if (length(omit)) ds <- ds[-omit,]

# Confirm the observations have been removed.

ds[vars] %>% nrow()
## [1] 61820
ds[vars] %>% is.na() %>% sum()
## [1] 0
# Restore the original dataset.

ds <- ods

Your donation will support ongoing development and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 1995-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.