R/add_squids_to_df.R

Defines functions add_squids_to_df

Documented in add_squids_to_df

#' Add a column with SQUIDs to a data frame
#'
#' @param x The data frame
#' @param colName The name of the column to add; set to `NULL` to return the
#' column instead of the data frame.
#' @param warnAgainstOverwriting Whether to throw an error if a column with
#' name `colName` already exists.
#' @inheritParams squids
#'
#' @returns If `colName = NULL`, the column with SQUIDs; otherwise, `x` with
#' an additional column named with the value of `colName`.
#' @export
#'
#' @examples squids::add_squids_to_df(
#'   mtcars
#' );
add_squids_to_df <- function(x,
                             colName = "SQUID",
                             warnAgainstOverwriting = TRUE,
                             origin = Sys.time(),
                             follow = NULL,
                             followBy = NULL) {

  if (!is.data.frame(x)) {
    stop("As `x`, you have to pass a data frame. However, the object you ",
         "passed has class(es) ", vecTxt(x), ".");
  }

  if (!is.null(colName) && (colName %in% names(x))) {
    if (warnAgainstOverwriting) {
      stop("The data frame you passed already has a column called `",
           colName, "`. If you're aware of this and want to replace ",
           "that column with a set of fancy new SQUIDs, you can pass ",
           "`warnAgainstOverwriting = FALSE`.");
    }
  }

  res <-
    squids::squids(
      x = nrow(x),
      origin = origin,
      follow = follow,
      followBy = followBy
    );

  if (is.null(colName)) {
    return(res);
  } else {
    x[[colName]] <- res;
    return(x);
  }

}

Try the squids package in your browser

Any scripts or data that you put into this service are public.

squids documentation built on June 8, 2025, 1:51 p.m.