Skip to content

Commit

Permalink
Allow cast era_yr -> character. Closes #11
Browse files Browse the repository at this point in the history
But not character -> era_yr for now, see # 38
  • Loading branch information
joeroe committed Mar 8, 2022
1 parent 3f05e17 commit 34f684a
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ S3method(vec_arith.era_yr,default)
S3method(vec_arith.era_yr,era_yr)
S3method(vec_arith.era_yr,numeric)
S3method(vec_arith.numeric,era_yr)
S3method(vec_cast,character.era_yr)
S3method(vec_cast,double.era_yr)
S3method(vec_cast,era.era)
S3method(vec_cast,era_yr.character)
S3method(vec_cast,era_yr.double)
S3method(vec_cast,era_yr.era_yr)
S3method(vec_cast,era_yr.integer)
Expand Down
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* More precise epoch value for Nowruz (Solar Hijri) eras: `621.2218` instead of `622`.
* `this_year()` now considers the current date, returns a floored integer (i.e. the actual current calendar year), and is vectorised over `era`.
* Class constructors `era()` and `yr()` return a zero-length vector when called with no arguments (instead of an error), allowing them to be used as [prototypes](https://vctrs.r-lib.org/articles/type-size.html)
* `era_yr` objects can be cast to character vectors (e.g. `as.character(yr(1, "BP"))`)

# era 0.3.1

Expand Down
10 changes: 10 additions & 0 deletions R/s3-yr.R
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,16 @@ vec_cast.era_yr.double <- function(x, to, ...) {
new_yr(x, yr_era(to))
}

#' @export
vec_cast.character.era_yr <- function(x, to, ...) {
paste(vec_data(x), era_label(yr_era(x)))
}

#' @export
vec_cast.era_yr.character <- function(x, to, ..., x_arg = "", to_arg = "") {
stop_incompatible_cast(x, to, x_arg = x_arg, to_arg = to_arg)
}

# Format/print ---------------------------------------------------------
#' @export
vec_ptype_full.era_yr <- function(x, ...) {
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-yr.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ test_that("era_yr cast methods return correct class", {
# double <-> era_yr
expect_type(vec_cast(new_yr(), double()), "double")
expect_s3_class(vec_cast(double(), new_yr()), "era_yr")

# character <-> era_yr
expect_type(vec_cast(new_yr(), character()), "character")
expect_error(vec_cast(character(), new_yr()),
class = "vctrs_error_incompatible_type")
})

test_that("casting era_yr to character returns expected output", {
expect_equal(vec_cast(yr(1:3, "BP"), character()), c("1 BP", "2 BP", "3 BP"))
})

test_that("format.era_yr returns expected output", {
Expand Down

0 comments on commit 34f684a

Please sign in to comment.