17
May 11

Simple R functions to keep or remove data frame columns

This function removes columns from a data frame by name:

removeCols <- function(data, cols){ return(data[,!names(data) %in% cols]) }

This function keeps columns of a data frame by name:

keepCols <- function(data, cols){
return(data[,names(data) %in% cols]) }

or just one function

colKeepRemove <- function(data, cols, remove=1){
if(remove == 1){ return(data[,!names(data) %in% cols]) }
else { return(data[,!names(data) %in% cols])  }}