R/string_manipulation.R

Defines functions myCollapse extract_trailing_year fromLastInstance toLastInstance

Documented in extract_trailing_year fromLastInstance myCollapse toLastInstance

#' A wrapper around paste(collapse)
#'
#' Collapses array into character string
#' @param array a character vector
#' @param sep a separator, defaults to '|'
#' @export
#' @examples
#' myCollapse()


myCollapse <- function(array, sep = '|'){
  array %>% paste(collapse = sep)
}


#' A function to extract a trailing year from a string
#'
#' Collapses array into character string
#' @param str a character string
#' @export
#' @examples
#' extract_trailing_year()

extract_trailing_year <- function(str){

  year <- stringr::str_remove(str,'\\.[a-z]+$') %>%
    stringr::str_extract_all('[0-9]{4}$') %>%
    as.character

  year

}


#' A function to extract the part of a string after the last instance of a regex
#'
#' Regex wrapper - find the last instance of a character and take only the string after that point
#' @param str a character string
#' @param split_on a regular expression
#' @export
#' @examples
#' fromLastInstance()
#'
fromLastInstance <- function(str,split_on){

  regex <- paste0(regex,'(?:.(?!',split_on,'))+$')

  return(str_extract(str,split_on))
}

#' A function to extract the part of a string before the last instance of a regex string
#'
#' Regex wrapper - find the last instance of a character and take only the string up to that point
#' @param str a character string
#' @param regular_exp a regular expression
#' @export
#' @examples
#' fromLastInstance()
#'


toLastInstance <- function(str, split_on ,drop_last = T){

  last <- str %>%
    str_locate_all(split_on) %>%
    unlist %>%
    max

  if(drop_last == T){
    str <- str_sub(str,1,last-1)
  } else {
    str <- str_sub(str,1,last)
  }


  return(str)


}
BillyEhrenberg/FTutilityfuncs documentation built on March 5, 2020, 12:42 a.m.