R Functions: Removing NA Columns

I realize that this might sound a little nerdy, but making simple and useful R functions can be quite fun.

Here are a couple of simple R functions i occasionally use that remove columns with NAs.

This function would remove all columns from a data frame that contain any NA values:

AnyNaCol = function(x) {
limit= ncol(x) 
for(i in limit:1){
if(anyNA(x[,i] == TRUE)) {x[,i] = NULL}
}
return(x)
}

And here’s one that would only remove those columns where all the values in the column are NA:

AllNaCol = function(x) {
limit= ncol(x)
for(i in limit:1){
if(sum(is.na(x[,i])) == nrow(x)) {x[,i] = NULL}
}
return(x)
}

I usually put all kinds of comments on my code, but i thought that this might be pretty straight forward.

This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *