Skip to content
Merged
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ repos:

# Format R files
- repo: https://github.com/lorenzwalthert/precommit
rev: v0.4.3.9029
rev: v0.4.3.9034
hooks:
- id: style-files
args: [
Expand Down
5 changes: 3 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,16 @@ Imports:
rlang,
tibble,
tidyselect,
utils
utils,
survival
Suggests:
knitr,
rmarkdown,
spelling,
testthat (>= 3.0.0)
VignetteBuilder:
knitr
Config/roxygen2/version: 8.1.0
Config/roxygen2/version: 8.1.1
Config/testthat/edition: 3
Encoding: UTF-8
Language: en-US
Expand Down
9 changes: 8 additions & 1 deletion NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Generated by roxygen2: do not edit by hand
importFrom("stats", "complete.cases")

export(acro_add_comments)
export(acro_add_exception)
export(acro_coxph)
export(acro_crosstab)
export(acro_custom_output)
export(acro_disable_rounding)
Expand All @@ -21,3 +22,9 @@ export(acro_rename_output)
export(acro_summarise)
export(acro_surv_func)
export(acro_table)
importFrom(stats,
complete.cases,
model.frame,
na.omit,
terms
)
2 changes: 1 addition & 1 deletion R/acro_init.R
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Globals -----------------------------------------------------------------
acro_venv <- "r-acro"
acro_pkg <- "acro==1.0.2"
acro_pkg <- "acro==1.1.0"
ch <- "conda-forge"


Expand Down
116 changes: 116 additions & 0 deletions R/acro_regression.R
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,119 @@ acro_glm <- function(formula, data, family) {
}
model$summary()
}

#' Fits a Cox proportional hazards regression model.
#'
#' @description
#' Fits a Cox proportional hazards model via ACRO. This function is designed
#' as a drop-in replacement for \code{survival::coxph()}.
#'
#' @details
#' Please note that multi-state models (using \code{istate} or \code{statedata})
#' and time-varying covariate models are currently not supported.
#'
Comment thread
JessUWE marked this conversation as resolved.
Resolved
#' @param formula a formula object, with the response on the left of a ~ operator, and the terms on the right. The response must be a survival object as returned by the Surv function.
#' @param data a data.frame in which to interpret the variables named in the formula, or in the subset and the weights argument.
#' @param weights vector of case weights
#' @param subset expression indicating which subset of the rows of data should be used in the fit. All observations are included by default.
#' @param na.action a missing-data filter function.
#' @param robust should a robust variance be computed.
#' @param init vector of initial values of the iteration.
#' @param cluster optional variable which clusters the observations, for the purposes of a robust variance. If present, it implies robust. This variable will normally be found in data.
#' @param istate optional variable giving the current state at the start each interval.
#' @param statedata optional data set used to describe multistate models.
#' @param ... Any other parameters.
#'
#' @returns Fitted CoxPHFitter results object
#' @export

#' @importFrom stats na.omit terms model.frame

acro_coxph <- function(formula, data, weights = NULL, subset = NULL, na.action = NULL, robust = TRUE, init = NULL, cluster = NULL, istate = NULL, statedata = NULL, ...) {
if (is.null(acroEnv$ac)) {
stop("ACRO has not been initialised. Please first call acro_init()")
}

# Check for multi-state model arguments (not supported by lifelines)
if (!is.null(istate) || !is.null(statedata)) {
stop("Multi-state models utilizing 'istate' or 'statedata' are not supported at the moment.")
}

model_data <- as.data.frame(data)

# Handle weights
weights_col <- NULL
if (!missing(weights)) {
res <- resolve_optional_column(substitute(weights), model_data, "weights", "acro_weight")
weights_col <- res$col_name
model_data <- res$data
}

# Handle cluster
cluster_col <- NULL
if (!missing(cluster)) {
res <- resolve_optional_column(substitute(cluster), model_data, "cluster", "acro_cluster")
cluster_col <- res$col_name
model_data <- res$data
robust <- TRUE # Clustering implies robust variance
}

# Handle subsetting if provided
if (!missing(subset)) {
subset_expr <- substitute(subset)
subsetted_columns <- eval(subset_expr, model_data)
model_data <- model_data[subsetted_columns & !is.na(subsetted_columns), ]
}

# Handle na.action
if (is.null(na.action)) {
na.action <- getOption("na.action")
}

na_function <- match.fun(na.action)
model_data <- na_function(model_data)

# Parse the formula to extract duration and event columns from the left-hand side
surv_func <- formula[[2]]
if (!inherits(surv_func, "call") || as.character(surv_func[[1]]) != "Surv") {
stop("The left-hand side of the formula must use Surv(), e.g., Surv(time, event) ~ x1 + x2")
}
duration_col <- as.character(surv_func[[2]])
event_col <- as.character(surv_func[[3]])

# Validate and transform event column for python lifelines
event_values <- unique(na.omit(model_data[[event_col]]))

if (all(event_values %in% c(1, 2))) {
model_data[[event_col]][model_data[[event_col]] == 1] <- 0
model_data[[event_col]][model_data[[event_col]] == 2] <- 1
} else if (!all(event_values %in% c(0, 1))) {
# If it's neither {1, 2} nor {0, 1}, throw an error
stop(paste0("In Surv(", duration_col, ", ", event_col, ") : Invalid status values"))
}

# Extract the right-hand side (independent variables) using terms()
trm <- terms(formula, data = model_data)
term_labels <- attr(trm, "term.labels")

# Collapse back into a robust formula string
independent_vars <- paste(term_labels, collapse = " + ")

# Check for any unused arguments
if (length(list(...)) > 0) {
warning("Unsupported arguments were provided: ", paste0(names(list(...)), collapse = ", "), "\n", "Please use the help command to learn more about the function.")
}

model <- acroEnv$ac$coxph(
df = model_data,
duration_col = duration_col,
event_col = event_col,
weights_col = weights_col,
robust = robust,
formula = independent_vars,
initial_point = init,
cluster_col = cluster_col
)

return(model)
}
2 changes: 2 additions & 0 deletions R/acro_tables.R
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ acro_table <- function(index, columns, dnn = NULL, deparse.level = 0, useNA = "n
#' @returns Summary of the data
#' @export

#' @importFrom stats complete.cases

acro_summarise <- function(.data, ..., .groups = NULL, .by = NULL) {
if (is.null(acroEnv$ac)) {
stop("ACRO has not been initialised. Please first call acro_init()")
Expand Down
49 changes: 30 additions & 19 deletions R/utils.R
Original file line number Diff line number Diff line change
@@ -1,23 +1,14 @@
#' Identify empty values; NA or NaN in an object
#'
#' @param Values to check for empty values in it
#'
#' @returns logical vector that shows the places of the empty values
#' @noRd

is_invalid <- function(Values) {
# Check for NA or NaN in the object
is.na(Values) | tolower(Values) %in% c("na", "nan")
}

#' Identify values to be excluded from an object
#'
#' @param Values to exclude from
#' @param exclude_list Items to exclude from the values
#'
#' @returns logical vector that shows the places of the items that needs to be excluded
#' @noRd

is_excluded <- function(Values, exclude_list) {
# Catch everything in the exclude list
mask <- Values %in% exclude_list
Expand All @@ -39,12 +30,7 @@ is_excluded <- function(Values, exclude_list) {

#' Convert data to factors and manage NA levels
#'
#' @param Values to create factors on
#' @param useNA whether to include NA values in the table
#'
#' @returns R vector factor
#' @noRd

create_factors <- function(Values, useNA) {
# Check for NAs
char_values <- as.character(Values)
Expand All @@ -64,12 +50,7 @@ create_factors <- function(Values, useNA) {

#' Convert an R factor to a Pandas Categorical
#'
#' @param Values R factor vector to be converted
#' @param pd Reference to the Python `pandas` module
#'
#' @returns A Python `pandas.Categorical` object
#' @noRd

to_pandas_categorical <- function(Values, pd) {
# Build the Pandas Categorical
pd$Categorical(
Expand All @@ -79,6 +60,7 @@ to_pandas_categorical <- function(Values, pd) {
)
}

#' @noRd
parse_summary_expression <- function(quo) {
expr <- rlang::quo_get_expr(quo)

Expand Down Expand Up @@ -117,6 +99,7 @@ parse_summary_expression <- function(quo) {
)
}

#' @noRd
get_offset_hist_breaks <- function(data, column, breaks = "sturges") {
# Extract the column from the data
r_column <- data[[column]]
Expand All @@ -131,3 +114,31 @@ get_offset_hist_breaks <- function(data, column, breaks = "sturges") {
}
return(breaks)
}


#' Helper to resolve external inputs (weights, cluster)
#' @noRd
## nocov start
resolve_optional_column <- function(expr, data, arg_name, prefix) {
optional_col <- NULL
if (!missing(expr)) {
col_expr <- substitute(optional_col)
if (!is.null(col_expr)) {
# If exp passed as a quoted character string matching a column name
if (is.character(col_expr) && col_expr %in% names(data)) {
optional_col <- col_expr
}
# If exp passed as an unquoted column name
else if (deparse(col_expr) %in% names(data)) {
optional_col <- deparse(col_expr)
}
# If exp passed as an external vector, expression, or function
else {
optional_col <- paste0("acro_additional_", sample(10000:99999, 1))
data[[optional_col]] <- eval(col_expr, data, parent.frame())
}
}
}
return(list(col_name = optional_col, data = data))
}
## nocov end
3 changes: 3 additions & 0 deletions inst/WORDLIST
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,6 @@ tidyverse
www
xlsx
yaml
CoxPHFitter
multistate
Surv
54 changes: 54 additions & 0 deletions man/acro_coxph.Rd

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

Loading
Loading