Skip to content

Commit

Permalink
Added coercion of matrix/array versions of mu and sigma, re. #18.
Browse files Browse the repository at this point in the history
  • Loading branch information
AEBilgrau committed Dec 27, 2018
1 parent 493b9a4 commit 5b7961b
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 4 deletions.
33 changes: 31 additions & 2 deletions R/as.theta.R
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
#' Coerce a list to a theta object
#'
#' @description At the moment, only the class is added.
#' First, the class is added. Next, matrix means and array covariances are
#' coerced to list form.
#' Covariances on array form are assumed to be \code{d} by \code{d} by \code{m}.
#' Means on matrix form are as assumed to be \code{d} by \code{m}. I.e.
#' rows correspond to the dimensions and colums to components, or the mean vectors
#' as column vectors.
#'
#' @param x A theta-like object that can be coerced.
#' @return A theta object. See \code{\link{rtheta}}.
#' @examples
#' m <- 2
#' d <- 2
#' d <- 3
#' x <- list(m = m,
#' d = d,
#' pie = c(0.5, 0.5),
Expand All @@ -15,9 +20,33 @@
#' print(x)
#' theta <- as.theta(x)
#' print(theta)
#'
#' x2 <- list(m = m,
#' d = d,
#' pie = c(0.5, 0.5),
#' mu = simplify2array(list(comp1=rep(0,d), comp2=rep(1,d))),
#' sigma = simplify2array(list(comp1=diag(d), comp2=diag(d))))
#' theta2 <- as.theta(x2)
#' print(theta2)
#' @export
as.theta <- function(x) {
class(x) <- "theta"

# Convert 'matrix' means to list
if (is.matrix(x[[4]]) && is.numeric(x[[4]])) {
stopifnot(nrow(x[[4]]) == x[[2]], # d
ncol(x[[4]]) == x[[1]]) # m
x[[4]] <- structure(lapply(seq_len(x[[1]]), function(j) x[[4]][, j]),
names = colnames(x[[4]]))
}

# Convert higher order array covariances to list
if (is.array(x[[5]]) && is.numeric(x[[5]])) {
stopifnot(dim(x[[5]]) == c(x[[2]], x[[2]], x[[1]]))
x[[5]] <- structure(lapply(seq_len(x[[1]]), function(k) x[[5]][, , k]),
names = dimnames(x[[5]])[[3]])
}

if (is.theta(x)) {
return(x)
} else {
Expand Down
17 changes: 15 additions & 2 deletions man/as.theta.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions tests/testthat/test-as.theta.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,15 @@ test_that("Check that as.theta works as intended", {
expect_true(is.theta(as.theta(x)))
suppressWarnings(expect_error(as.theta(x[-4])))
})

# Coercion tests
d <- 3
x2 <- list(m = m,
d = d,
pie = c(0.5, 0.5),
mu = simplify2array(list(comp1 = rep(0,d), comp2 = rep(1,d))),
sigma = simplify2array(list(comp1 = diag(d), comp2 = diag(d))))

test_that("Check that as.theta works for 'matrix means'", {
expect_true(is.theta(as.theta(x2)))
})

0 comments on commit 5b7961b

Please sign in to comment.