R/x_to_null.R

Defines functions x_if_null

Documented in x_if_null

#' Maintain indices with missing information in a list containing NULL values
#'
#' If a list contains NULL values, calling unlist on it will create a vector-like object that loses the index/indices containing NULL. If one-to-one mappings are required, this results in information mismatch.
#'
#' @param list The list object that may or may not contain NULL values.
#' @param x The value that NULL is to be replaced with - defaults to 0.
#' @param cores If the function is to be parallelised, enter the number of cores here. Defaults to one.
#' @keywords unlist NULL keep
#' @export
#' @import parallel
#' @examples
#' NULLlist <- list(1, 2, 3, NULL, 5, NULL, 7, 8, NULL, 10)
#'
#' unlist(NULLlist)
#' [1] 1 2 3 5 7 8 10
#'
#' x_if_null(NULLlist = NULLlist, x = 'Nothing')
#' [1] "1"       "2"       "3"       "Nothing" "5"       "Nothing" "7"       "8"       "Nothing" "10"

x_if_null <- function(NULLlist, x = 0, cores = 1) {

  NULLlist %>%
    mclapply(mc.cores = cores,
             FUN = function(n) {

      ifelse(test = is.null(n),
             yes = x,
             no = n)

      }) %>%
    unlist

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