R/init_if_absent.R

Defines functions init_if_absent

Documented in init_if_absent

#' Initializes an object with a value only if an object with the same name is
#' absent in the environment
#'
#' Get a name (as "character"), checks if there is an object with that name
#' exists, if it does it leaves the object untouched. If it does not exists,
#' sets it to "value". Returns messages indicating what happened. If an object
#' is given it checks the value inside the object and if it is "character" the
#' function uses this string to name the object.
#'
#' @param name name to be used on object assignment.
#' @param value value to give pass to the object.
#' @keywords assign
#' @export
#' @examples
#' init_if_absent("y", 1:10)
#' init_if_absent("y", 11:20) # repeating does not change its value
#'
#' name <- "var1"
#' init_if_absent(name, 200:100)
#' var1
#' name

init_if_absent <-
  function(name, value) {
    if(!exists(name)) {
      assign(name, value, pos = parent.frame())
      cat(name, "was created with the value:", head(value), "...\n")
    } else {
      cat(name, "was not created because it already exists.\n")
    }
  }
mtcruz/mtcruzr documentation built on Dec. 26, 2019, 11:04 p.m.