R/slice_head.R

Defines functions duckplyr_slice_head slice_head.duckplyr_df

Documented in slice_head.duckplyr_df

# Generated by 02-duckplyr_df-methods.R
#' @rdname slice_head.duckplyr_df
#' @export
slice_head.duckplyr_df <- function(.data, ..., n, prop, by = NULL) {
  if (!missing(n)) {
    n_valid <- (n >= 0)
  } else {
    n_valid <- TRUE
  }

  # Our implementation
  duckplyr_error <- rel_try(NULL,
    #' @section Fallbacks:
    #' There is no DuckDB translation in `slice_head.duckplyr_df()`
    #' - if `by` or `prop` is provided,
    #' - with a negative `n`.
    #'
    #' These features fall back to [slice_head()], see `vignette("fallback")` for details.
    "{.code slice_head(by = ...)} not supported" = !missing(by),
    "{.code slice_head(prop = ...)} not supported" = !missing(prop),
    "{.code slice_head(n = ...)} with negative values not supported" = !n_valid,
    {
      rel <- duckdb_rel_from_df(.data)
      out_rel <- rel_limit(rel, n)
      out <- duckplyr_reconstruct(out_rel, .data)
      return(out)
    }
  )

  # dplyr forward
  check_prudence(.data, duckplyr_error)

  slice_head <- dplyr$slice_head.data.frame
  out <- slice_head(.data, ..., n = n, prop = prop, by = {{ by }})
  return(out)

  # dplyr implementation
  check_dots_empty0(...)

  size <- get_slice_size(n = n, prop = prop)
  idx <- function(n) {
    seq2(1, size(n))
  }

  dplyr_local_error_call()
  dplyr_local_slice_by_arg("by")

  slice(.data, idx(dplyr::n()), .by = {{ by }})
}

duckplyr_slice_head <- function(.data, ...) {
  try_fetch(
    .data <- as_duckplyr_df_impl(.data),
    error = function(e) {
      testthat::skip(conditionMessage(e))
    }
  )
  out <- slice_head(.data, ...)
  class(out) <- setdiff(class(out), "duckplyr_df")
  out
}

Try the duckplyr package in your browser

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

duckplyr documentation built on June 8, 2025, 10:53 a.m.