R/list_remove.R

Defines functions list_remove

Documented in list_remove

#' Remove (Named) Elements from a List.
#'
#' Jettison names or indices of a list and retain everything else (including names).
#' @keywords list remove element keep retain
#' @param mylist A list object that has superfluous elements.
#' @param element A vector (either character or numeric) of elements to drop from 'mylist'.
#' @export
#' @examples
#' testlist <- list('first' = c(1:3), 'second' = 2, 'third' = c(4:9), 'last' = 'hello')
#' list_remove(mylist = testlist, element = c('first', 'third'))
#' $second
#' [1] 2
#'
#' $last
#' [1] "hello"

list_remove <- function(mylist, element) {

  if ( is.null(element) ) { stop('The list element(s) must be defined. See function help for details.') }
  if ( class(mylist) != 'list' ) { stop('The mylist argument must actually be a list.') }

  if ( class(element) == 'character' ) {

    if ( any(duplicated(element)) ) { stop('All elements must be unique.') }
    if ( !all(element %in% names(mylist) ) ) { stop('Everything listed in "element" should be a name of "mylist".') }
    # First check that all of the elements in 'element' are names or mylist

    element <-
      lapply(X = element,
             FUN = function(e) { which(names(mylist) == e) }) %>%
      unlist
    # Then reassign 'element' with the indices that are to be removed.

  }

  keep <- which(!(1:length(mylist) %in% element))
  # Store indices of names and arguments to retain.

  newlist <- lapply(X = keep, FUN = function(k) { mylist[[k]] })

  if ( !is.null(names(mylist)) ) { names(newlist) <- names(mylist)[keep] }

  return(newlist)

}
danjamesadams/Dantools documentation built on Aug. 24, 2019, 6:15 p.m.