Skip to content

Commit

Permalink
[ and [[ keep attributes (#275)
Browse files Browse the repository at this point in the history
* [ and [[ keep attributes

* Keep pillar attribute to ensure formatting survives subsetting

* Only test pillar attribute

* Update R/make_units.R

Co-authored-by: Iñaki Ucar <iucar@fedoraproject.org>
  • Loading branch information
krlmlr and Enchufa2 authored Mar 25, 2021
1 parent 63a345d commit c644c3f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
10 changes: 6 additions & 4 deletions R/conversion.R
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,14 @@ as_difftime <- function(x) {


#' @export
`[.units` <- function(x, i, j, ..., drop = TRUE)
.as.units(NextMethod(), units(x))
`[.units` <- function(x, i, j, ..., drop = TRUE) {
restore_units(NextMethod(), x)
}

#' @export
`[[.units` <- function(x, i, j, ...)
.as.units(NextMethod(), units(x))
`[[.units` <- function(x, i, j, ...) {
restore_units(NextMethod(), x)
}

#' @export
as.POSIXct.units = function (x, tz = "UTC", ...) {
Expand Down
6 changes: 6 additions & 0 deletions R/make_units.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
structure(x, units = value, dim = dim, class = "units")
}

restore_units <- function(x, to) {
out <- .as.units(x, units(to))
attr(out, "pillar") <- attr(to, "pillar")
out
}

#' @name units
#' @export
#'
Expand Down
8 changes: 8 additions & 0 deletions tests/testthat/test_misc.R
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,11 @@ test_that("str works", {
str(set_units(1/1:3, m/s))
})
})

test_that("subsetting keeps pillar attribute (#275)", {
x <- set_units(1:3, m)
attr(x, "pillar") <- "bar"

expect_equal(attr(x[1:2], "pillar"), "bar")
expect_equal(attr(x[[1]], "pillar"), "bar")
})

0 comments on commit c644c3f

Please sign in to comment.