stan-dev / posterior

The posterior R package
https://mc-stan.org/posterior/
Other
167 stars 24 forks source link

Errors when `rvar` is made from a data frame #363

Closed mattansb closed 6 months ago

mattansb commented 6 months ago

Some funny things happen when an rvar is made from a data frame. To make a long story short, these can all be traced back to this:

x <- data.frame(
  x1 = rnorm(1000),
  x2 = rnorm(1000)
)

# Seems to work, but tends to throw errors...
r <- posterior::rvar(x, nchains = 2)
r
#> rvar<500,2>[2] mean ± sd:
#>            x1            x2 
#> 0.021 ± 1.03  0.013 ± 0.99

str(r)
#> Error in dim(.draws) <- c(.dim[1], prod(.dim[-1])) : 
#>   dims [product 2000] do not match the length of object [2]

# If you first convert to a matrix, everything is fine:
r <- posterior::rvar(as.matrix(x), nchains = 2)
r
#> rvar<500,2>[2] mean ± sd:
#>            x1            x2 
#> 0.021 ± 1.03  0.013 ± 0.99

str(r)
#>  rvar<500,2>[2]  0.021 ± 1.03  0.013 ± 0.99
#>  - dimnames(*)=List of 1
#>   ..$ : chr [1:2] "x1" "x2"
mjskay commented 6 months ago

Heh, oh yeah that definitely shouldn't allow you to do that.

mjskay commented 6 months ago

Thanks for raising this, added a PR to fix. Basically, you should not be able to input a data.frame into rvar(). If all the columns in the data frame are of the same type, convert to a matrix first (as you did), and if they aren't, consider using as_draws_rvars() instead of rvar() to convert each column to an rvar instead of the entire data frame to a single rvar.

mattansb commented 6 months ago

Thanks!