R/rm.empty.cols.R

Defines functions rm.empty.cols

Documented in rm.empty.cols

#' Remove Empty Columns From an Imported Excel Sheet
#' @description \command{rm.empty.cols} removes columns that have only \code{NAs} \emph{AND} whose names
#'     start with a capital 'X' (unless \option{na.only} is \code{TRUE} in which case all \code{NA} columns
#'     will be removed).
#' @param x (\code{data.frame}). A data frame resulting from an imported Excel sheet by means of \command{read.xls}
#' @param na.only (\code{logical}). Should all 'NA' columns be removed and not only those with a column name starting
#'     with X as generated by Excel (see details section)?
#' @details Empty columns in Excel sheets are imported to \code{NA} columns in the resulting data frame.
#'     Columns that did not have a column name in the spread sheet will result in data frame column names
#'     starting with 'X'. \command{rm.empty.cols} makes use of these two criteria to identify columns that
#'     can safely be removed from the data frame.
#' @return A data frame.
#' @keywords utilities
#' @export
rm.empty.cols <-
function(x, na.only = FALSE)
{
  
  allna <- apply(x, 2, function(z) all(is.na(z)))
  if (!na.only) X <- sapply(colnames(x), function(z) length(grep("^X", z))) > 0
  else X <- !logical(ncol(x))
  nac <- which(apply(data.frame(allna, X), 1, all))
  if (length(nac) > 0) { x <- x[, -nac] }
  return(x)

}

Try the readmoRe package in your browser

Any scripts or data that you put into this service are public.

readmoRe documentation built on Aug. 19, 2021, 9:07 a.m.