How to delete columns that contain ONLY NAs?

Lorenzo Rigamonti picture Lorenzo Rigamonti · Apr 12, 2013 · Viewed 107.4k times · Source

I have a data.frame containing some columns with all NA values, how can I delete them from the data.frame.

Can I use the function

na.omit(...) 

specifying some additional arguments?

Answer

Ciarán Tobin picture Ciarán Tobin · Apr 12, 2013

One way of doing it:

df[, colSums(is.na(df)) != nrow(df)]

If the count of NAs in a column is equal to the number of rows, it must be entirely NA.

Or similarly

df[colSums(!is.na(df)) > 0]