Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle lists correctly in nth.() #535

Merged
merged 3 commits into from
Jul 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* `across.()`: Can namespace functions in `.fns` arg (#511)
* `as_tidytable()`: Can keep row names when converting a matrix (#527)
* `unnest.()`: Handles empty data frames (@roboton, #530)
* `nth.()`: Extracts list elements (#534)

# tidytable 0.8.0

Expand Down
28 changes: 24 additions & 4 deletions R/first-last-nth.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,19 @@
#' first.(vec)
#' last.(vec)
#' nth.(vec, 4)
first. <- function(x, default = NA, na_rm = FALSE) {
first. <- function(x, default = NULL, na_rm = FALSE) {
nth.(x, 1L, default, na_rm)
}

#' @rdname first.
#' @export
last. <- function(x, default = NA, na_rm = FALSE) {
last. <- function(x, default = NULL, na_rm = FALSE) {
nth.(x, -1L, default, na_rm)
}

#' @rdname first.
#' @export
nth. <- function(x, n, default = NA, na_rm = FALSE) {
nth. <- function(x, n, default = NULL, na_rm = FALSE) {
if (na_rm) {
x <- x[!vec_equal_na(x)]
}
Expand All @@ -41,7 +41,27 @@ nth. <- function(x, n, default = NA, na_rm = FALSE) {
}

if (n > size || n == 0) {
vec_cast(default, vec_ptype(x))
nth_default(x, default)
} else {
vec_slice2(x, n)
}
}

nth_default <- function(x, default) {
if (vec_is_list(x)) {
out <- default
} else {
if (is.null(default)) {
default <- NA
}
out <- vec_cast(default, vec_ptype(x))
}
out
}

vec_slice2 <- function(x, n) {
if (vec_is_list(x)) {
.subset2(x, n)
} else {
vec_slice(x, n)
}
Expand Down
6 changes: 3 additions & 3 deletions man/first..Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions tests/testthat/test-first-last-nth.R
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,10 @@ test_that("work on data frames", {
expect_equal(first.(df), head(df, 1))
expect_equal(last.(df), tail(df, 1))
})

test_that("work on lists", {
l <- list(x = "x", y = "y")
expect_equal(first.(l), "x")
expect_equal(last.(l), "y")
expect_equal(nth.(l, 3), NULL)
})