Skip to content

Commit

Permalink
Merge pull request #268 from stan-dev/issue-265
Browse files Browse the repository at this point in the history
ensure as_draws_rvars preserves dims of length-1 arrays, closes #265
  • Loading branch information
mjskay committed Jan 25, 2023
2 parents 879bb0f + 7d74707 commit 539ec2f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
* Implemented faster `vec_proxy.rvar()` and `vec_restore.rvar()`, improving
performance of `rvar`s in `tibble`s (and elsewhere `vctrs` is used).

### Bug Fixes

* Ensure that `as_draws_rvars()` preserves dimensions of length-1 arrays (#265).


# posterior 1.3.1

Expand Down
5 changes: 3 additions & 2 deletions R/as_draws_rvars.R
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,9 @@ as_draws_rvars.draws_matrix <- function(x, ...) {
var_i <- vars == var
var_matrix <- x_at(var_i)
attr(var_matrix, "nchains") <- NULL
var_indices <- vars_indices[var_i]

if (ncol(var_matrix) == 1) {
if (ncol(var_matrix) == 1 && nchar(var_indices[[1]][[3]]) == 0) {
# single variable, no indices
out <- rvar(var_matrix)
dimnames(out) <- NULL
Expand All @@ -91,7 +92,7 @@ as_draws_rvars.draws_matrix <- function(x, ...) {

# first, pull out the list of indices into a data frame
# where each column is an index variable
indices <- vapply(vars_indices[var_i], `[[`, i = 3, character(1))
indices <- vapply(var_indices, `[[`, i = 3, character(1))
indices <- as.data.frame(do.call(rbind, strsplit(indices, ",")),
stringsAsFactors = FALSE)
unique_indices <- vector("list", length(indices))
Expand Down
8 changes: 8 additions & 0 deletions tests/testthat/test-as_draws.R
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,14 @@ test_that("as_draws_rvars can accept lists of lists as input", {
expect_equal(as_draws_rvars(example_draws()), as_draws_rvars(list_of_lists))
})

test_that("as_draws_rvars preserves dims of length-1 arrays", {
draws_array <- draws_array(`x[1,1,1]` = 1:5)
expect_equal(
draws_of(as_draws_rvars(draws_array)$x),
array(1:5, dim = c(5, 1, 1, 1), dimnames = list(1:5, NULL, NULL, NULL))
)
})

test_that("draws_df does not munge variable names", {
draws_df <- draws_df(`x[1]` = 1:2, `x[2]` = 3:4)
expect_equal(variables(draws_df), c("x[1]", "x[2]"))
Expand Down

0 comments on commit 539ec2f

Please sign in to comment.