R/adds.R

Defines functions add_rowindex

Documented in add_rowindex

#' Add a column of row numbers to a data frame
#'
#' @param x A data frame
#' @return The same data frame with a column of 1-based integers named `.row`.
#' @examples
#' mtcars %>% add_rowindex()
#' @export
#' @importFrom dplyr mutate
add_rowindex <- function(x) {
  if (!is.data.frame(x)) {
    rlang::abort("`x` should be a data frame.")
  }
  if (nrow(x) > 0) {
    x <- dplyr::mutate(x, .row = 1:nrow(x))
  } else {
    x$.row <- integer(0)
  }
  x
}

Try the parsnip package in your browser

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

parsnip documentation built on July 21, 2021, 5:08 p.m.