Remove columns from dataframe where some of values are NA
The data:
Itun <- data.frame(v1 = c(1,1,2,1,2,1), v2 = c(NA, 1, 2, 1, 2, NA))
This will remove all columns containing at least one NA
:
Itun[ , colSums(is.na(Itun)) == 0]
An alternative way is to use apply
:
Itun[ , apply(Itun, 2, function(x) !any(is.na(x)))]
Here's a convenient way to do it using the dplyr
function select_if()
. Combine not (!
), any()
and is.na()
, which is equivalent to selecting all columns that don't contain any NA values.
library(dplyr)
Itun %>%
select_if(~ !any(is.na(.)))