R/nulls.R

#' Functions for dealing with NULL elements of a list
#'
#' Convert all the \code{NULL} elements of list to \code{NA}s
#' using \code{nulls_to_nas}. The \code{unlist_with_nas} function
#' is an equivalent of \code{\link{unlist}} that replaces
#' all the \code{NULL} entries with \code{NA}'s instead of
#' dropping them. Function \code{drop_nulls} non-recursively
#' removes the \code{NULL} entries of a list.
#'
#' @param x    a list.
#' @param null the replacement value for \code{NULL} elements.
#'
#' @examples
#'
#' lst <- list(1, 2, NULL, 3, 4:6, list(NULL, 7, 8), as.list(9:11))
#' names(lst) <- letters[seq_along(lst)]
#'
#' nulls_to_nas(lst)
#' unlist_with_nas(lst)
#' drop_nulls(lst)
#'
#' @export

nulls_to_nas <- function(x, null = NA) {
  lapply(x, function(elem) {
    if (is.null(elem) || length(elem) == 0L)
      return(null)
    if (is_simple_list(elem))
      return(nulls_to_nas(elem))
    elem
  })
}

#' @rdname nulls_to_nas
#' @export

unlist_with_nas <- function(x, null = NA) {
  if (!is.list(x))
    return(x)
  unlist(nulls_to_nas(x))
}

#' @rdname nulls_to_nas
#' @export

drop_nulls <- function(x) {
  is_not_null <- function(elem) {
    isTRUE(!is.null(elem) && length(elem) > 0L)
  }
  Filter(is_not_null, x)
}
twolodzko/lolplyr documentation built on May 14, 2019, 8:22 a.m.