Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More code cleaning, mostly in calcBalStat #109

Merged
merged 4 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Imports:
survey,
jtools,
mice,
mitml,
stargazer,
gtools,
cobalt,
Expand Down
68 changes: 37 additions & 31 deletions R/assessBalance.R
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@


assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome, type, formulas, weights = NULL, balance_thresh = 0.1,
imp_conf = NULL, verbose = TRUE, save.out = TRUE){
imp_conf = NULL, verbose = TRUE, save.out = TRUE) {

if (!is.logical(save.out)) {
stop("`save.out` must be a flag (TRUE or FALSE)",
Expand All @@ -130,6 +130,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
stop("Please supply a home directory.",
call. = FALSE)
}

else if(!is.character(home_dir)){
stop("Please provide a valid home directory path as a string if you wish to save output locally.",
call. = FALSE)
Expand All @@ -150,6 +151,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
stop("Please provide either a 'mids' object, a data frame, or a list of imputed csv files in the 'data' field.",
call. = FALSE)
}

else if(is.list(data) && !is.data.frame(data)){
if (sum(sapply(data, is.data.frame)) != length(data)){
stop("Please supply a list of data frames that have been imputed.",
Expand Down Expand Up @@ -196,15 +198,17 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
stop("Please provide a list of formulas for each exposure time point",
call. = FALSE)
}
else if(is.list(formulas) && !is.data.frame(formulas)){
else if (is.list(formulas) && !is.data.frame(formulas)) {
if (sum(sapply(formulas, function(x) {

inherits(x, "formula")})) != length(formulas)){
stop("Please supply a list of formulas for each exposure time point.",
call. = FALSE)
}
}



if (missing(type)){
stop("Please supply a 'weighted', 'prebalance' type",
call. = FALSE)
Expand Down Expand Up @@ -232,12 +236,14 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
call. = FALSE)
}


if (!is.null(weights) && (!is.list(weights) || is.data.frame(weights))){
stop("Please supply a list of weights output from the createWeights function.",
call. = FALSE)
}
else if(is.list(weights) && !is.data.frame(weights)){
else if (is.list(weights) && !is.data.frame(weights)) {
if (sum(sapply(weights, function(x) {

inherits(x, "weightitMSM")})) != length(weights)){
stop("Please supply a list of weights output from the createWeights function.",
call. = FALSE)
Expand Down Expand Up @@ -286,7 +292,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
folder <- switch(type, "prebalance" = "prebalance/", "weighted/")


if (save.out){
if (save.out) {
balance_dir <- file.path(home_dir, "balance")
if (!dir.exists(balance_dir)) {
dir.create(balance_dir)
Expand Down Expand Up @@ -326,14 +332,14 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,

d <- as.data.frame(mice::complete(data, k))

if (anyNA(d)){
if (anyNA(d)) {
stop("This code requires complete data. Consider imputation if missingness < 20% and is reasonably Missing at Random (MAR).",
call. = FALSE)
}

exposure_type <- if (is.numeric(d[, paste0(exposure, '.', exposure_time_pts[1])])) "continuous" else "binary"

if (sum(duplicated(d$"ID")) > 0){
if (sum(duplicated(d$"ID")) > 0) {
stop("Please provide wide imputed datasets with a single row per ID.", call. = FALSE)
}

Expand All @@ -343,19 +349,19 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
}
else {

m = length(data)
m <- length(data)

bal_stats <- lapply(seq_len(m), function(k) {
d <- data[[k]]

if (anyNA(d)){
if (anyNA(d)) {
stop("This code requires complete data. Consider imputation if missingness < 20% and is reasonably Missing at Random (MAR).",
call. = FALSE)
}

exposure_type <- if (is.numeric(d[, paste0(exposure, '.', exposure_time_pts[1])])) "continuous" else "binary"
exposure_type <- if (is.numeric(d[[paste0(exposure, '.', exposure_time_pts[1])]])) "continuous" else "binary"

if (sum(duplicated(d[["ID"]])) > 0){
if (sum(duplicated(d[["ID"]])) > 0) {
stop("Please provide wide imputed datasets with a single row per ID.", call. = FALSE)
}

Expand All @@ -369,10 +375,10 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
bal_stats_all_imp <- bal_stats_all_imp[order(bal_stats_all_imp$covariate), ]


if (save.out){
if (save.out) {
write.csv(bal_stats_all_imp, sprintf("%s/balance/%s/%s_all_imps_balance_stat_summary.csv",
home_dir, type, exposure))
if (verbose ){
if (verbose ) {
cat("Pre balance statistics for each imputed dataset have now been saved in the 'balance/prebalance/' folder", "\n")
}

Expand All @@ -390,7 +396,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,

#adds custom bal thresh info

if (!is.null(imp_conf)){
if (!is.null(imp_conf)) {

all_bal_stats$bal_thresh <- ifelse(all_bal_stats$covariate %in% imp_conf,
balance_thresh[1], balance_thresh[2])
Expand All @@ -406,7 +412,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
}


if (verbose){
if (verbose) {
cat("\n")
cat(paste0("*** Averaging Across All Imputations ***"), "\n")
}
Expand All @@ -416,7 +422,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
else {


if (sum(duplicated(data[["ID"]])) > 0){
if (sum(duplicated(data[["ID"]])) > 0) {
stop("Please provide wide dataset with a single row per ID.", call. = FALSE)
}

Expand All @@ -425,7 +431,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
call. = FALSE)
}

exposure_type <- if (is.numeric(data[, paste0(exposure, '.', exposure_time_pts[1])])) "continuous" else "binary"
exposure_type <- if (is.numeric(data[[paste0(exposure, '.', exposure_time_pts[1])]])) "continuous" else "binary"

bal_stats <- calcBalStats(home_dir, data, formulas, exposure, exposure_time_pts, outcome,
balance_thresh, k = 0, weights = NULL, imp_conf, verbose, save.out)
Expand Down Expand Up @@ -462,11 +468,11 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
bal_stats <- lapply(seq_len(m), function(k) {
d <- as.data.frame(mice::complete(data, k))

if (anyNA(d)){
if (anyNA(d)) {
stop("This code requires complete data. Consider imputation if missingness < 20% and is reasonably Missing at Random (MAR).",
call. = FALSE)
}
if (sum(duplicated(d[["ID"]])) > 0){
if (sum(duplicated(d[["ID"]])) > 0) {
stop("Please provide wide imputed datasets with a single row per ID.", call. = FALSE)
}

Expand All @@ -482,11 +488,11 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
bal_stats <- lapply(seq_len(m), function(k) {
d <- data[[k]]

if (anyNA(d)){
if (anyNA(d)) {
stop("This code requires complete data. Consider imputation if missingness < 20% and is reasonably Missing at Random (MAR).",
call. = FALSE)
}
if (sum(duplicated(d[["ID"]])) > 0){
if (sum(duplicated(d[["ID"]])) > 0) {
stop("Please provide wide imputed datasets with a single row per ID.", call. = FALSE)
}

Expand All @@ -502,10 +508,10 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
bal_stats_all_imp <- do.call(dplyr::bind_rows, bal_stats)
bal_stats_all_imp <- bal_stats_all_imp[order(bal_stats_all_imp$covariate), ]

if (save.out){
if (save.out) {
write.csv(bal_stats_all_imp, sprintf("%s/balance/%s/%s_all_imps_balance_stat_summary.csv",
home_dir, type, exposure))
if (verbose){
if (verbose) {
cat("Weighted balance statistics for each imputed dataset have now been saved in the 'balance/weighted/' folder", "\n")
}
}
Expand All @@ -520,9 +526,9 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
avg_bal = rowMeans(do.call(cbind, lapply(bal_stats, `[[`, "std_bal_stats"))))

# #adds custom bal thresh info
if (!is.null(imp_conf)){
if (!is.null(imp_conf)) {

all_bal_stas$bal_thresh <-ifelse(all_bal_stats$covariate %in% imp_conf,
all_bal_stats$bal_thresh <-ifelse(all_bal_stats$covariate %in% imp_conf,
balance_thresh[1], balance_thresh[2])

all_bal_stats$balanced <- ifelse(abs(all_bal_stats$avg_bal) <
Expand All @@ -544,7 +550,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
}
else {

if (sum(duplicated(data$"ID")) > 0){
if (sum(duplicated(data$"ID")) > 0) {
stop("Please provide wide dataset with a single row per ID.", call. = FALSE)
}

Expand Down Expand Up @@ -596,7 +602,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
data_type, balance_thresh, weights_method, imp_conf, verbose, save.out)
})

if (save.out){
if (save.out) {
outfile <- sprintf("%s/balance/%s/%s-%s_all_%s_%s_associations.html",
home_dir, type, exposure, outcome, type, weights_method)

Expand All @@ -613,8 +619,8 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
sink()


if (verbose){
if (mi){
if (verbose) {
if (mi) {
cat(sprintf("Summary plots for %s %s averaged across all imputations have been saved out for each time point in the 'balance/%s/plots/' folder.\n",
form_name, exposure, type))
}
Expand All @@ -632,7 +638,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
row.names = FALSE)


if (verbose){
if (verbose) {
if (mi) {
cat(sprintf("Check 'balance/%s/' folder for a table of all %s correlations or
standardized mean differences averaged across imputed datasets.\n",
Expand All @@ -655,7 +661,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
"[", 1)[!duplicated(sapply(strsplit(unbalanced_covars$covariate, "\\."), "[", 1))]


if (verbose){
if (verbose) {
if (mi) {
cat(sprintf("USER ALERT: Averaging across all imputed datasets for exposure %s using the %s formulas and %s :\n",
exposure, form_name, weights_method))
Expand Down Expand Up @@ -695,7 +701,7 @@ assessBalance <- function(home_dir, data, exposure, exposure_time_pts, outcome,
round(min(all_bal_stats$avg_ba), 2),
round(max(all_bal_stats$avg_ba), 2)))

if (nrow(unbalanced_covars) > 0){
if (nrow(unbalanced_covars) > 0) {
# cat(paste0("As shown below, the following ", nrow(unbalanced_covars), " covariates across time points out of ",
# length(tot_covars), " total (", round(nrow(unbalanced_covars) / length(tot_covars) * 100, 2), "%) spanning ",
# length(unbalanced_constructs), " domains out of ", length(tot_cons), " (", round(length(unbalanced_constructs) / length(tot_cons) * 100, 2),
Expand Down
Loading
Loading