R/misc.R

Defines functions tryElse is.installed codes rep_along

Documented in codes is.installed rep_along tryElse

#' Try an Expression Otherwise Return a Value
#' 
#' @export
 
tryElse <- function(expr, error = NULL, warn = TRUE) {
  tryCatch(expr, error = function(x) {
      if (warn) warning(x)
      error
    })
}


#' Check if packages are installed
#' 
#' @param \dots list of package names.
#' 
#' @importFrom utils installed.packages
#' @export

is.installed <- function(..., exact = TRUE) {
  x <- unlist(list(...))
  stopifnot(is.character(x))
  pkgs <- installed.packages()[, 1]
  if (exact) {
    structure(x %in% pkgs, names=x)
  } else {
    sapply(x, function(y) grep(y, pkgs, ignore.case = TRUE, value = TRUE))
  }
}


#' Print factor labels
#' 
#' @param x factor vector
#' 
#' @export

codes <- function(x) {
  structure(1:nlevels(x), names=levels(x))
}


#' Replicate Elements of Vectors 
#' 
#' @param along.with take the length from the length of this argument.
#' @param x vector.
#' 
#' @export

rep_along <- function(x, along.with) {
  rep(x, length.out = length(along.with))
}
twolodzko/twextras documentation built on May 3, 2019, 1:52 p.m.