R/whichcol.R

Defines functions whichcol

Documented in whichcol

#' Which column
#'
#' Retrieves column names and labels that matches a general expression via
#' \link[base]{grepl}.
#' 
#' @param tibble a tibble object.
#' @param label a logical value indicating if pattern should be searched in
#' variable label, instead of variable name. Default is \code{TRUE}.
#' @inheritParams base::grepl
#' @inheritDotParams base::grepl
#'
#' @returns A data frame.
#' 
#' @keywords tibblemanagement
#' 
#' @examples
#' # tibble generated by haven
#' input <- system.file("extdata/reds", package = "ILSAmerge")
#' x <- do.call(rbind,justload(inputdir = input,population = "BCGV1"))
#' x
#' 
#' whichcol("weight",x)
#'
#' @export
#

whichcol <- function(pattern, tibble, label = TRUE, ignore.case = TRUE, ...){
  
  
  # Checks ------------------------------------------------------------------
  
  if(!inherits(tibble, "tbl_df"))
    stop(c("\nInvalid input for 'tibble'.",
           "\nIt should be a tibble."),call. = FALSE)
  
  if(!(isTRUE(label)|isFALSE(label)))
    stop(c("\nInvalid input for 'label'.",
           "\nIt should be a logical value."),call. = FALSE)
  
  # Process & Output --------------------------------------------------------
  
 
  cols <- unlist(get.atr(tibble, "label", NULLasNA = TRUE))
  
  if(label){
    coltos <- cols
  }else{
    coltos <- colnames(tibble)
  }
  
  out <- colnames(tibble)[grepl(pattern,coltos, ignore.case = ignore.case, ...)]
  
  
  out <- cbind.data.frame(name = out, 
                          label = cols[grepl(pattern,coltos, ignore.case = ignore.case, ...)])
  rownames(out) <- NULL
  return(out)
}

Try the ILSAmerge package in your browser

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

ILSAmerge documentation built on April 11, 2025, 5:54 p.m.