Skip to content

Commit

Permalink
added c.epiparameter and c.multi_epiparameter functions, fixes #351
Browse files Browse the repository at this point in the history
  • Loading branch information
joshwlambert committed Aug 13, 2024
1 parent 6a6c869 commit 481667f
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ S3method(as.data.frame,epiparameter)
S3method(as.data.frame,multi_epiparameter)
S3method(as.function,epiparameter)
S3method(as_epiparameter,data.frame)
S3method(c,epiparameter)
S3method(c,multi_epiparameter)
S3method(cdf,epiparameter)
S3method(convert_params_to_summary_stats,character)
S3method(convert_params_to_summary_stats,epiparameter)
Expand Down
59 changes: 59 additions & 0 deletions R/epiparameter.R
Original file line number Diff line number Diff line change
Expand Up @@ -920,3 +920,62 @@ mean.epiparameter <- function(x, ...) {
# return mean or NA
mean
}

#' [c()] method for `<epiparameter>` class
#'
#' @param ... [dots] Objects to be concatenated.
#'
#' @return An `<epiparameter>` or list of `<epiparameter>` objects.
#' @export
#'
#' @examples
#' db <- epiparameter_db()
#'
#' # combine two <epiparameter> objects into a list
#' c(db[[1]], db[[2]])
#'
#' # combine a list of <epiparameter> objects and a single <epiparameter> object
#' c(db, db[[1]])
c.epiparameter <- function(...) {
x <- list(...)
if (!all(vapply(x, FUN = inherits, FUN.VALUE = logical(1),
what = c("epiparameter", "multi_epiparameter")))) {
stop(
"Can only combine <epiparameter> or <multi_epiparameter> objects",
call. = FALSE
)
}

# if <multi_epiparameter> are in `...` build the new unnested list of
# <epiparameter> objects iteratively in order to preserve input order
if (any(vapply(x, FUN = inherits, FUN.VALUE = logical(1),
what = "multi_epiparameter"))) {
# list is not pre-allocated as it's easier to append arbitrary length
# <multi_epiparameter> objects
ep_list <- list()
for (i in seq_along(x)) {
if (is_epiparameter(x[[i]])) {
ep_list <- c(ep_list, list(x[[i]]))
} else {
# unclass to prevent recursive dispatch
ep_list <- c(ep_list, unclass(x[[i]]))
}
}
} else {
ep_list <- x
}

# for when `...` is a single <epiparameter>
if (length(ep_list) == 1) {
ep_list <- ep_list[[1]]
} else {
# will always be triggered if called from c.multi_epiparameter
class(ep_list) <- "multi_epiparameter"
}
ep_list
}

#' @export
c.multi_epiparameter <- function(...) {
c.epiparameter(...)
}
26 changes: 26 additions & 0 deletions man/c.epiparameter.Rd

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

0 comments on commit 481667f

Please sign in to comment.