Skip to content

Commit

Permalink
lead(), lag(): cast default to common type rather than to type of x. (t…
Browse files Browse the repository at this point in the history
…idyverse#5181)

* lead(), lag(): cast default to common type rather than to type of x.

closes bergsmat/wrangle#1

* Using vec_cast_common() from @lionel- review
  • Loading branch information
romainfrancois committed May 4, 2020
1 parent 8710f8a commit c5b7be3
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
13 changes: 7 additions & 6 deletions R/lead-lag.R
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,11 @@ lag <- function(x, n = 1L, default = NA, order_by = NULL, ...) {
xlen <- vec_size(x)
n <- pmin(n, xlen)

default <- vec_cast(default, x, x_arg = "default", to_arg = "x")
inputs <- vec_cast_common(default = default, x = x)

vec_c(
vec_rep(default, n),
vec_slice(x, seq_len(xlen - n))
vec_rep(inputs$default, n),
vec_slice(inputs$x, seq_len(xlen - n))
)
}

Expand All @@ -87,9 +88,9 @@ lead <- function(x, n = 1L, default = NA, order_by = NULL, ...) {
xlen <- vec_size(x)
n <- pmin(n, xlen)

default <- vec_cast(default, x, x_arg = "default", to_arg = "x")
inputs <- vec_cast_common(default = default, x = x)
vec_c(
vec_slice(x, -seq_len(n)),
vec_rep(default, n)
vec_slice(inputs$x, -seq_len(n)),
vec_rep(inputs$default, n)
)
}
2 changes: 1 addition & 1 deletion tests/testthat/test-lead-lag-errors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ incompatible default
====================

> lag(c("1", "2", "3"), default = FALSE)
Error: Can't convert `default` <logical> to `x` <character>.
Error: Can't combine `default` <logical> and `x` <character>.

0 comments on commit c5b7be3

Please sign in to comment.