content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Compare Probability of an Event with Benchmark #' #' @param data dataset #' @param column name of column #' @param benchmark benchmark #' @param event specify event as given in column (example: 0, "pass", "success") #' @param count number of times event has occurred. Use only when using input = "values" #' @param total total number of all events. Use only when using input = "values" #' @param event_type Optional: a string describing the type of event. For example, success, failure, etc. #' @param notes whether output should contain minimal or technical type of notes. Defaults to "minimal". Use "none" to turn off. #' @param remove_missing TRUE/FALSE (Default is TRUE) #' @param input Default: "long" - long form of data, "values" to pass values directly. If using this option, must specify count and total. #' @param output Default: "console" - prints output in console and returns tibble invisibly. #' @return Dataframe of results when saved to an object. Show console output by default #' @export #' @import magrittr #' @importFrom huxtable position map_align print_screen by_cols as_hux #' @importFrom stringr str_detect #' @importFrom stats dbinom #' @importFrom scales percent #' @importFrom tibble as_tibble rownames_to_column #' @importFrom cli cli_h1 cli_text #' @examples #' data <- data.frame(task_1 = c("y", "y", "y", "y", "n", "n", "n", NA, NA, NA, NA, NA, NA, NA), #' task_2 = c(0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1)) #' # With dataframe columns #' #' benchmark_event(data, column = task_1, benchmark = 0.8, event = "y") #' benchmark_event(data, column = task_2, benchmark = 0.3, event = 1, event_type = "success") #' #' # Also pipeable #' data |> #' benchmark_event(column = task_2, benchmark = 0.3, event = 1, event_type = "success") #' #' # With direct values #' benchmark_event(benchmark = 0.8, count = 4, total = 7, input = "values") benchmark_event <- function(data, column, benchmark, event, count, total, event_type = "", remove_missing = TRUE, notes = "minimal", input = "long", output = "console") { if (input == "long") { column <- deparse(substitute(column)) if (remove_missing == TRUE) { total <- length(data[[column]][!is.na(data[[column]])]) } else { total <- length(data[[column]]) } event_count <- table(data[[column]])[[event]] } else if (input == "values") { event_count <- count total <- total } result <- 1 - sum(dbinom(event_count:total, prob = benchmark, size = total)) probability <- round(result, 3) rate <- event_count |> divide_by(total) |> percent(2) benchmark_text <- benchmark |> percent() result_percent <- result |> percent() if (event_type == "") { event_type <- "event" } # notes output_text <- match.arg(notes) none <- "" minimal <- paste( "Based on the", event_type, paste0("rate of ", rate, ","), "the probability that this rate exceeds a benchmark of", benchmark_text, "is", result_percent ) technical <- paste( "Probability values were computed based on the binomial distribution", "With the", event_type, paste0("rate of ", rate, ","), "the probability that this rate exceeds a benchmark of", benchmark_text, "is", result ) # result table result_table <- as_tibble(data.frame( count = event_count, total = total, benchmark = benchmark, result = result, probability = probability, output_text = switch(output_text, none = none, minimal = minimal, technical = technical ) )) if (notes == "none") { result_table <- result_table |> select(-output_text) } # print table result_table_print <- result_table |> t() |> data.frame() |> rownames_to_column("term") |> data.frame() |> rename(result = 2) |> as_hux() huxtable::position(result_table_print) <- "left" result_print <- result_table_print |> filter(!str_detect(term, "output_text")) result_print <- map_align(result_print, by_cols("left", "right")) # return if (output == "console") { cli_h1("Compare Event Rate with a Benchmark") cli_text(result_table$output_text) print_screen(result_print, colnames = FALSE) return(invisible(result_table)) } else if (output == "tibble") { return(result_table) } }
/scratch/gouwar.j/cran-all/cranData/uxr/R/benchmark_event.R
#' Compare Score with a Benchmark #' @param data dataframe #' @param column a column of scores from the dataframe #' @param benchmark benchmark #' @param mean if input = "values", enter mean value #' @param sd if input = "values", enter standard deviation value #' @param n if input = "values", enter total number of scores #' @param tail one-tailed or two-tailed test #' @param remove_missing TRUE/FALSE (Default is TRUE) #' @param input Default: "long" - long form of data, "values" to pass values directly. If using this option, must specify mean, sd, and n. #' @param output Default: "console" - prints output in console and returns tibble invisibly. #' @return dataframe of results when saved to an object. show console output by default #' @export #' @importFrom huxtable position map_align print_screen by_cols as_hux #' @importFrom stats pt sd na.omit #' @examples #' scores <- 80 + 23 * scale(rnorm(172)) # 80 = mean, 23 = sd #' data <- data.frame(scores = scores) #' benchmark_score(data, scores, 67) #' data |> benchmark_score(scores, 67) #' benchmark_score(mean = 80, sd = 23, n = 172, benchmark = 67, input = "values") benchmark_score <- function(data, column, benchmark, mean, sd, n, tail = "one", remove_missing = TRUE, input = "long", output = "console") { column <- deparse(substitute(column)) if(missing(mean)) { mean <- NULL } if(missing(sd)) {sd <- NULL} if(missing(n)) {n <- NULL} if (input == "long") { mean <- mean(data[[column]], na.rm = remove_missing) sd <- sd(data[[column]], na.rm = remove_missing) if (remove_missing == TRUE) { n <- length(na.omit(data[[column]])) } else { n <- length(data[[column]]) } } else if (input == "values") { mean <- mean sd <- sd n <- n } df <- n - 1 t <- (mean - benchmark) / (sd / sqrt(n)) if (tail == "one") { probability <- dist_t(t, df, tail = "one") } else if (tail == "two") { probability <- dist_t(t, df, tail = "two") } else { stop("arguments for tail must be 'one' or 'two'") } confidence <- 1 - probability se <- sd / sqrt(n) margin_of_error <- t * se lower_ci <- mean - margin_of_error upper_ci <- mean + margin_of_error output_text <- paste( "We can be", paste0(round(confidence, 2) * 100, "%"), "confident that the true score is between", round(lower_ci, 2), "and", round(upper_ci, 2) ) result_table <- as_tibble(data.frame( mean = mean, sd = sd, se = se, n = n, df = df, probability = probability, tail = tail, confidence = confidence, margin_of_error = margin_of_error, t = t, lower_ci = lower_ci, upper_ci = upper_ci, output_text = output_text )) result_table_print <- result_table |> t() |> data.frame() |> tibble::rownames_to_column("term") |> data.frame() |> dplyr::rename(result = 2) |> as_hux() if (output == "console") { cli::cli_h1("Compare Score with a Benchmark") cli::cli_text(result_table$output_text) huxtable::position(result_table_print) <- "left" result_print <- result_table_print |> dplyr::filter(!stringr::str_detect(term, "output_text")) result_print <- map_align(result_print, by_cols("left", "right")) print_screen(result_print, colnames = FALSE) return(invisible(result_table)) } else if (output == "tibble") { return(result_table) } }
/scratch/gouwar.j/cran-all/cranData/uxr/R/benchmark_score.R
#' Compare Time with a Benchmark #' @param data dataframe #' @param column a column or vector of time values #' @param benchmark benchmark #' @param alpha alpha #' @param remove_missing TRUE/FALSE (Default is TRUE) #' @param input Default: "long" - long form of data, "values" to pass values directly. If using this option, must specify count and total. #' @param output Default: "console" - prints output in console and returns tibble invisibly. #' @return lower_ci, upper_ci, t, probability #' @export #' @importFrom stats pt sd #' @importFrom huxtable position map_align print_screen by_cols as_hux #' @examples #' data <- data.frame(time = c(60, 53, 70, 42, 62, 43, 81)) #' benchmark_time(data, column = time, benchmark = 60, alpha = 0.05) benchmark_time <- function(data, column, benchmark, alpha, remove_missing = FALSE, input = "long", output = "console") { column <- deparse(substitute(column)) if(input == "long") { if (remove_missing == TRUE) { n <- length(na.omit(data[[column]])) } else { n <- length(data[[column]]) } t <- (log(benchmark) - mean(log(data[[column]]), na.rm = remove_missing))/(sd(log(data[[column]]), na.rm = remove_missing)/sqrt(n)) df <- n-1 } probability <- pt(q = t, df = df, lower.tail = FALSE) se <- sd(log(data[[column]]))/sqrt(n) t1<- qt(p=alpha/2, df,lower.tail=F) lower_ci <- exp(mean(log(data[[column]]), na.rm = remove_missing) - se*t1) upper_ci <- exp(mean(log(data[[column]]), na.rm = remove_missing) + se*t1) result_table <- as_tibble(data.frame(lower_ci = lower_ci, upper_ci = upper_ci, t = t, probability = probability)) result_print <- result_table |> t() |> data.frame() |> tibble::rownames_to_column("term") |> data.frame() |> as_hux() if(output == "console") { huxtable::position(result_print) <- "left" cli::cli_h1("Compare Time with a Benchmark") result_print <- result_print |> dplyr::filter(!stringr::str_detect(term, "output_text")) result_print <- map_align(result_print, by_cols("left", "right")) print_screen(result_print, colnames = FALSE) return(invisible(result_table)) } else if (output == "tibble") { return(result_table) } }
/scratch/gouwar.j/cran-all/cranData/uxr/R/benchmark_time.R
#' Compare Means Between Groups #' #' @param data data #' @param var1 variable 1 #' @param var2 variable 2 #' @param variable variable #' @param grouping_variable Group #' @param groups Specify groups from grouping variable #' @param test Default: "Welch", choose between "student" and "Welch" #' @param input Default: "wide", choose between "long" and "wide". "wide" requires data var1 var2. "long" requires data, variable, grouping_variable groups #' @param output Default: "console" - prints output in console and returns tibble invisibly. #' @return results #' @importFrom huxtable position map_align print_screen by_cols as_hux #' @importFrom dplyr filter rename mutate #' @importFrom tidyr pivot_wider #' @importFrom tibble rownames_to_column #' @importFrom stringr str_remove #' @importFrom stats as.formula t.test #' @export #' @examples #' #' # Wide data - default #' data_wide <- data.frame(A = c(4, 2, 5, 3, 6, 2, 5), #' B = c(5, 2, 1, 2, 1, 3, 2)) #' #' compare_means_between_groups(data_wide, var1 = A, var2 = B) #' #' # Long data #' data_long <- data_wide |> tibble::rowid_to_column("id") |> #' tidyr::pivot_longer(cols = -id, names_to = "group", values_to = "variable") #' #' compare_means_between_groups(data_long, variable = variable, #' grouping_variable = group, groups = c("A", "B"), input = "long") compare_means_between_groups <- function(data, var1, var2, variable, grouping_variable, groups, test = "Welch", input = "wide", output = "console") { if (input == "wide") { var1 <- deparse(substitute(var1)) var2 <- deparse(substitute(var2)) if (test == "student") { result <- t.test(data[[var1]], data[[var2]], var.equal = TRUE) } else if (test == "Welch") { result <- t.test(data[[var1]], data[[var2]], var.equal = FALSE) } result <- t.test(data[[var1]], data[[var2]]) x_name <- deparse(substitute(var1)) x_name <- sub(".*\\$", "", x_name) y_name <- deparse(substitute(var2)) y_name <- sub(".*\\$", "", y_name) means <- result$estimate names(means)[1] <- x_name names(means)[2] <- y_name means <- data.frame(means) |> rownames_to_column("variables") |> as_tibble() means$variables <- gsub('[\"]', "", means$variables) means <- means |> mutate(variables = paste0("mean_of_", variables)) means <- means |> pivot_wider(names_from = variables, values_from = means) } if (input == "long") { lhs <- deparse(substitute(variable)) rhs <- deparse(substitute(grouping_variable)) formula <- as.formula(paste(lhs, "~", rhs)) data <- data %>% # Note: needs %>% pipe filter({{ grouping_variable }} %in% groups) if (test == "student") { result <- stats::t.test(formula, data = data, var.equal = TRUE) } else if (test == "Welch") { result <- stats::t.test(formula, data = data, var.equal = FALSE) } means <- result$estimate |> data.frame() |> rownames_to_column("variables") |> rename(means = 2) |> mutate(variables = str_remove(variables, "mean in group ")) |> mutate(variables = paste0("mean_of_", variables)) |> pivot_wider(names_from = variables, values_from = means) } ## for both wide and long ci <- result$conf.int |> t() |> data.frame() |> dplyr::rename( lower_ci = X1, upper_ci = X2 ) ci_level <- attributes(result$conf.int) |> unlist() p_value <- result$p.value t <- result$statistic df <- result$parameter result_table <- means |> bind_cols(as_tibble(data.frame(t = t, df = df, p_value = p_value, ci_level = ci_level))) |> bind_cols(ci) if (output == "console") { cli::cli_h1(result$method) result_print <- result_table |> t() |> data.frame() |> rownames_to_column("term") |> rename(value = 2) result_print <- result_print |> as_hux() huxtable::position(result_print) <- "left" result_print <- map_align(result_print, by_cols("left", "right")) print_screen(result_print, colnames = FALSE) return(invisible(result_table)) } else if (output == "tibble") { return(result_table) } }
/scratch/gouwar.j/cran-all/cranData/uxr/R/compare_means_between_groups.R
#' Compare Means Within Groups #' #' @param data dataframe #' @param var1 variable 1 #' @param var2 variable 2 #' @param input Default: "long" - long form of data, "values" to pass values directly. If using this option, must specify mean, sd, and n. #' @param output Default: "console" - prints output in console and returns tibble invisibly. #' @importFrom huxtable position map_align print_screen by_cols as_hux #' @return results #' @export #' @examples #' data <- data.frame(id = c(1:7), #' task1 = c(4, 1, 2, 3, 8, 4, 4), #' task2 = c(7, 13, 9, 7, 18, 8, 10)) #' compare_means_within_groups(data, task1, task2) compare_means_within_groups <- function(data, var1, var2, input = "wide", output = "console") { lower_ci <- upper_ci <- X1 <- X2 <- NULL var1 <- deparse(substitute(var1)) var2 <- deparse(substitute(var2)) if(input == "wide") { result <- stats::t.test(data[[var1]], data[[var2]], paired = TRUE) } result_table <- result$estimate |> data.frame() |> t() |> data.frame() ci <- result$conf.int |> t() |> data.frame() |> dplyr::rename( lower_ci = X1, upper_ci = X2 ) |> dplyr::mutate( lower_ci = round(lower_ci, 2), upper_ci = round(upper_ci, 2) ) ci_level <- attributes(result$conf.int) |> unlist() result_table <- result_table |> dplyr::mutate( t = round(result$statistic, 2), p = scales::pvalue(result$p.value), df = round(result$parameter), ci_level = ci_level ) |> dplyr::bind_cols(tibble::tibble(ci)) |> t() |> data.frame() |> tibble::rownames_to_column(" ") |> data.frame() if(output == "console") { cli::cli_h1("Compare Means Within Groups") result_print <- result_table |> as_hux() huxtable::position(result_print) <- "left" result_print <- map_align(result_print, by_cols("left", "right")) print_screen(result_print, colnames = FALSE) return(invisible(result_table)) } else if(output == "tibble") { return(result_table) } }
/scratch/gouwar.j/cran-all/cranData/uxr/R/compare_means_within_groups.R
#' Compare Rates Between Groups #' #' @param data data #' @param group column in dataframe : group #' @param event column in dataframe : event #' @param test Type of test (fisher, n-1 two prop) #' @param input Defaults to "long" #' @param output "console" prints output to console; "tibble" returns tibble #' @return results #' @export #' @examples #' design = c("A","B") #' complete = c(34, 24) #' incomplete = c(317, 301) #' data <- data.frame(design, complete, incomplete) #' data <- data |> tidyr::pivot_longer(!design, names_to = "rate", values_to = "n") |> #' tidyr::uncount(n) #' compare_rates_between_groups(data, group = design, event = rate) compare_rates_between_groups <- function(data, group, event, test, input = "long", output = "console") { if(missing(test)) {test = ""} if(input == "long") { table <- table_observed_expected(data, {{group}}, {{event}}) expected <- min(table$expected) if(test == "fisher") { cli::cli_h1("Compare Rates Between Groups") cli::cli_alert("Fisher's Test") result <- test_fisher(data, {{group}}, {{event}}) } else if (test == "n_1_prop") { cli::cli_h1("Compare Rates Between Groups") cli::cli_alert("N-1 Two Proportions test") result <- test_n_1_prop(data, {{group}}, {{event}}) } else if (test == "") { if(expected < 1) { cli::cli_h1("Compare Rates Between Groups") cli::cli_alert("Fisher's Test") result <- test_fisher(data, {{group}}, {{event}}) } else if (expected >= 1) { cli::cli_h1("Compare Rates Between Groups") cli::cli_alert("N-1 Two Proportions test") result <- test_n_1_prop(data, {{group}}, {{event}}) } } } result_table <- result |> data.frame() |> t() |> data.frame() |> rownames_to_column("term") |> rename(value = 2) if(output == "console") { result_print <- result_table |> as_hux() huxtable::position(result_print) <- "left" result_print <- map_align(result_print, by_cols("left", "right")) print_screen(result_print, colnames = FALSE) return(invisible(result_table)) } else if (output == "tibble") { return(result) } }
/scratch/gouwar.j/cran-all/cranData/uxr/R/compare_rates_between_groups.R
#' Compare Rates Within Groups #' #' @param data data #' @param x var 1 #' @param y var 2 #' @param conf_level Confidence level #' @param input input type currently only accepts "wide" #' @param output Default is "console", also accepts "tibble" #' @importFrom dplyr bind_cols rename #' @importFrom tibble as_tibble #' @return results #' @export #' @examples #' A <- c(1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1) #' B <- c(0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0) #' data <- data.frame(A, B) #' compare_rates_within_groups(data, A, B, input = "wide") compare_rates_within_groups <- function(data, x, y, conf_level = 0.95, input, output = "console") { if(missing(input)) { stop("please specify input = 'wide'")} conf_int <- get_confidence_intervals_within_groups(data, x, y, conf_level) test <- test_mcnemar(data, x, y) |> as_tibble() |> rename(p_value = value) result <- bind_cols(test, conf_int) if(output == "console") { cli::cli_h1("Compare Rates Within Groups") cli::cli_alert("McNemar's Test") result_print <- result |> as_hux() huxtable::position(result_print) <- "left" result_print <- map_align(result_print, by_cols("left", "right")) print_screen(result_print, colnames = FALSE) return(invisible(result)) } else if (output == "tibble") { return(result) } }
/scratch/gouwar.j/cran-all/cranData/uxr/R/compare_rates_within_groups.R
/scratch/gouwar.j/cran-all/cranData/uxr/R/datasets.R
#' T Distribution #' #' @param t t #' @param df degrees of freedom #' @param tail 'one' or 'two' #' @return value #' @export #' @importFrom stats pt #' @examples #' dist_t(1.4, 2, "one") #' dist_t(1.4, 2, "two") dist_t <- function(t, df, tail) { if (tail == "one") { pt(-abs(t), df) } else if(tail == "two") { 2 * pt(-abs(t), df) } else { stop("tail must be 'one' or 'two'") } }
/scratch/gouwar.j/cran-all/cranData/uxr/R/dist_t.R
#' Get concordant and discordant pairs for two variables #' #' @param data = data #' @param x variable 1 #' @param y variable 2 #' @return a data frame #' @importFrom tidyr pivot_longer pivot_wider replace_na #' @importFrom dplyr mutate case_when count select relocate left_join #' @importFrom stringr str_replace #' @importFrom tibble deframe rowid_to_column add_row #' @importFrom utils globalVariables #' @importFrom stats chisq.test #' @export #' @examples #' mtcars$id <- seq.int(nrow(mtcars)) #' get_concordant_discordant_pairs(mtcars, x = vs, y = am) get_concordant_discordant_pairs <- function(data, x, y) { x_name <- deparse(substitute(x)) y_name <- deparse(substitute(y)) table <- data |> select({{x}}, {{y}}) |> rowid_to_column("id") |> pivot_longer(cols = -id) |> mutate(value = as.numeric(factor(value))-1) |> pivot_wider() |> mutate(pairs = case_when( {{x}} > {{y}} ~ "b", {{x}} < {{y}} ~ "c", {{x}} + {{y}} == 2 ~ "a", {{x}} + {{y}} == 0 ~ "d")) |> count(pairs) if ("a" %in% table$pairs == FALSE) { table <- table |> add_row(pairs = "a") } if ("b" %in% table$pairs == FALSE) { table <- table |> add_row(pairs = "b") } if ("c" %in% table$pairs == FALSE) { table <- table |> add_row(pairs = "c") } if ("d" %in% table$pairs == FALSE) { table <- table |> add_row(pairs = "d") } table <- table |> mutate(type = case_when(pairs == "a" ~ "concordant: x = 1 & y = 1", pairs == "d" ~ "concordant: x = 0 & y = 0", pairs == "b" ~ "discordant: x = 1 & y = 0", pairs == "c" ~ "discordant: x = 0 & y = 1")) |> mutate(type = str_replace(type, 'x', x_name)) |> mutate(type = str_replace(type, 'y', y_name)) |> mutate(n = replace_na(n, 0)) return(table) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/get_concordant_discordant_pairs.R
#' Get Confidence Intervals for Event Rate #' #' @param event event #' @param total total #' @param confidence_level confidence level as z value #' @return lower_ci, upper_ci #' @export #' @examples #' get_confidence_intervals_event(event = 80, #' total = 100, #' confidence_level = 1.96) get_confidence_intervals_event <- function(event, total, confidence_level) { adjusted_proportion <- function(event, total, confidence_level) { p_adj <- (event + confidence_level^2/2)/(total + confidence_level^2) p_adj } p_adj <- adjusted_proportion(event, total, confidence_level) p <- p_adj total <- total + confidence_level*2 value <- confidence_level*(sqrt((p*(1-p)/total))) lower_ci <- p - value upper_ci <- p + value list(lower_ci = lower_ci, upper_ci = upper_ci) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/get_confidence_intervals_event.R
get_confidence_intervals_score <- function(data, alpha, remove_missing = TRUE) { na.rm <- remove_missing mean <- mean(data, na.rm = na.rm) sd <- sd(data, na.rm = na.rm) n <- length(data) df <- n-1 standard_error <- sd/sqrt(n) t <- abs(qt(p = alpha/2, df = df)) margin_of_error <- t*standard_error lower_ci <- mean - margin_of_error upper_ci <- mean + margin_of_error list(mean = mean, sd = sd, n = n, df = df, alpha = alpha, margin_of_error = margin_of_error, t = t, lower_ci = lower_ci, upper_ci = upper_ci, text_output = paste("We can be", paste0(((1-alpha)*100), "%"), "confident that the true score is between", round(lower_ci, 2), "and", round(upper_ci, 2))) } get_confidence_intervals_score(c(1, 2, 3, NA, 5, 6), 0.05)
/scratch/gouwar.j/cran-all/cranData/uxr/R/get_confidence_intervals_score.R
#' Get Confidence Intervals Within Groups #' #' @param data data #' @param x var 1 #' @param y var 2 #' @param conf_level Confidence level #' @importFrom dplyr bind_cols rename summarise pull #' @importFrom tibble as_tibble #' @return results #' @export #' @examples #' A <- c(1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1) #' B <- c(0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0) #' data <- data.frame(A, B) #' get_confidence_intervals_within_groups(data, A, B) get_confidence_intervals_within_groups <- function(data, x, y, conf_level = 0.95) { z <- abs(qnorm((1 - conf_level) / 2)) adj_pairs <- get_concordant_discordant_pairs(data, x, y) |> mutate(adj = (z^2) / 8) |> mutate(adj_n = n + adj) N_adj <- adj_pairs |> summarise(sum = sum(adj_n)) |> pull() p1_adj <- adj_pairs |> filter(pairs %in% c("a", "b")) |> pull(adj_n) |> sum() |> divide_by(N_adj) p2_adj <- adj_pairs |> filter(pairs %in% c("a", "c")) |> pull(adj_n) |> sum() |> divide_by(N_adj) p12_adj <- adj_pairs |> filter(pairs == "b") |> pull(adj_n) |> divide_by(N_adj) p21_adj <- adj_pairs |> filter(pairs == "c") |> pull(adj_n) |> divide_by(N_adj) ci <- ((p12_adj + p21_adj) - raise_to_power((p21_adj - p12_adj), 2)) |> divide_by(N_adj) |> sqrt() |> multiply_by(z) if (p1_adj > p2_adj) { lower_ci <- (p1_adj - p2_adj) - ci upper_ci <- (p1_adj - p2_adj) + ci } else { lower_ci <- (p2_adj - p1_adj) - ci upper_ci <- (p2_adj - p1_adj) + ci } return(data.frame( lower_ci = lower_ci, upper_ci = upper_ci )) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/get_confidence_intervals_within_groups.R
#' Mean Confidence Intervals #' #' @param x values #' @param alpha alpha #' #' @return lower_ci, upper_ci #' @export #' @importFrom stats median qt #' @examples #' stat_mean_ci(c(1, 2, 3, 4, 5, 6, 7), 1.96) #' stat_mean_ci(c(2, 4, 6, 8), 1.96) stat_mean_ci <- function(x, alpha) { log <- log(x) mean <- mean(log) sd <- sd(log) n <- length(x) df <- n-1 se <- sd(log)/sqrt(n) t<- qt(p=alpha/2, df,lower.tail=F) lower_ci <- ceiling(exp(mean - se*t)) upper_ci <- ceiling(exp(mean + se*t)) list(lower_ci = lower_ci, upper_ci = upper_ci) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/stat_mean_ci.R
#' Mean Confidence Intervals (Large Samples) #' #' @param x values #' @param z z value #' #' @return lower_ci, upper_ci #' @export #' @importFrom stats median #' @examples #' stat_mean_ci_2(c(1, 2, 3, 4, 5, 6, 7), 1.96) #' stat_mean_ci_2(c(2, 4, 6, 8), 1.96) stat_mean_ci_2 <- function(x, z) { n <- length(x) p <- 0.5 # percentile (0.5) for the median se <- sqrt(n*(p*(1-p))) me <- z*se lower_ci <- n*p - me upper_ci <- n*p + me sorted <- sort(x) lower_ci <- dplyr::nth(sorted, ceiling(lower_ci)) # use ceiling instead of rounding upper_ci <- dplyr::nth(sorted, ceiling(upper_ci)) list(lower_ci = lower_ci, median = median(x), upper_ci = upper_ci) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/stat_mean_ci_2.R
#' Observed Expected Table #' #' @param data data #' @param x x #' @param y y #' @importFrom stats chisq.test #' @importFrom dplyr relocate left_join #' @importFrom rlang := #' @return results #' @export table_observed_expected <- function(data, x, y) { table <- suppressWarnings(chisq.test( summarise(data, tab = list(table({{x}}, {{y}})))$tab[[1]])) observed <- table$observed |> as_tibble(.name_repair = ~ c("x", "y", "observed")) expected <- table$expected |> as_tibble(rownames = "x") |> pivot_longer(-1, names_to="y", values_to = "expected") observed |> left_join(expected, by = c("x", "y")) |> mutate(diff = observed-expected) |> mutate(diff2 = diff^2) |> mutate(component = diff2/expected) |> mutate({{x}} := x) |> mutate({{y}} := y) |> select(-x, -y) |> relocate({{x}}, {{y}}) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/table_observed_expected.R
#' Chi-squared One Sample #' #' @param data data #' @param x x #' @importFrom dplyr mutate count distinct summarise #' @importFrom tidyr uncount #' @return results #' @export #' @examples #' data <- tibble::tribble(~fruit, ~count, #' "Apple" , 29, #' "Banana" , 24, #' "Cucumber" , 22, #' "Dragon Fruit" , 19 #' ) #' #' data <- data |> #' tidyr::uncount(weights = count) |> #' tibble::rowid_to_column("id") #' #' test_chisq_one(data, fruit) test_chisq_one <- function(data, x) { case_total <- nrow(data) distinct_groups <- nrow(distinct(data, {{x}})) table <- data |> count({{x}}, name = "observed") |> mutate(expected = case_total/distinct_groups) |> mutate(residual = observed - expected) |> mutate(residual_sq = residual^2) |> mutate(component = residual_sq/expected) chi_sq <- table |> summarise(chi_sq = sum(component)) chi_sq_result <- chi_sq chi_sq_result }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_chisq_one.R
#' Chi-squared Two Sample #' #' @param data data #' @param x x #' @param y y #' @importFrom stats pchisq #' @return results #' @export #' @examples #' data <- tibble::tribble(~fruit, ~count, #' "Apple" , 29, #' "Banana" , 24, #' "Cucumber" , 22, #' "Dragon Fruit" , 19 #' ) #' #' data <- data |> #' tidyr::uncount(weights = count) |> #' tibble::rowid_to_column("id") #' #' test_chisq_one(data, fruit) test_chisq_two <- function(data, x, y) { table <- table_observed_expected(data, {{x}}, {{y}}) chi_sq <- sum(table$component) p_value <- pchisq(chisq, 2, lower.tail = FALSE) cat("chisq :",chi_sq, "\n") cat("df :", 2, "\n") cat("p_value :", p_value) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_chisq_two.R
#' Fisher's Test #' #' @param data data #' @param x x #' @param y y #' @importFrom dplyr summarise #' @importFrom stats fisher.test #' @return results #' @export #' @examples #' design = c("A","B") #' complete = c(11, 5) #' incomplete = c(1, 5) #' data <- data.frame(design, complete, incomplete) #' data <- data |> tidyr::pivot_longer(!design, names_to = "rate", values_to = "n") |> #' tidyr::uncount(n) #' test_fisher(data, design, rate) test_fisher <- function(data, x, y) { table <- summarise(data, tab = list(table({{x}}, {{y}})))$tab[[1]] result <- fisher.test(table) as_tibble(data.frame(p_value = result$p.value, odds_ratio = unname(result$estimate) )) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_fisher.R
#' McNemar Test #' #' @param data data #' @param x var 1 #' @param y var 2 #' @return results #' @importFrom huxtable position map_align print_screen by_cols as_hux #' @importFrom dplyr filter rename mutate #' @importFrom stats as.formula #' @export #' @examples #' A <- c(1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1) #' B <- c(0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0) #' data <- data.frame(A, B) #' test_mcnemar(data, A, B) test_mcnemar <- function(data, x, y) { discordant_pairs <- get_concordant_discordant_pairs(data, x, y) |> filter(pairs %in% c("b", "c")) |> select(pairs, n) |> deframe() |> as.list() x <- discordant_pairs |> unlist() |> sum() y <- discordant_pairs |> unlist() |> min() y <- c(0:y) factorial_fun <- function(x, y) { a <- factorial(x) / (factorial(y) * factorial(x - y)) b <- (0.5 ^ y) * (1 - 0.5) ^ (x - y) a * b } r <- lapply(x, factorial_fun, y = y) sum(r[[1]])*2 }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_mcnemar.R
#' N-1 Two Proportions Test #' #' @param data data #' @param x x #' @param y y #' @param conf_level Confidence Level (default = 0.95) #' @importFrom dplyr ungroup group_by slice #' @importFrom tidyr complete #' @importFrom stats pnorm qnorm #' @return results #' @export #' @examples #' design = c("A","B") #' complete = c(37, 22) #' incomplete = c(418, 416) #' data <- data.frame(design, complete, incomplete) #' data <- data |> tidyr::pivot_longer(!design, names_to = "rate", values_to = "n") |> #' tidyr::uncount(n) #' test_n_1_prop(data, design, rate, conf_level = 0.95) test_n_1_prop <- function(data, x, y, conf_level = 0.95) { z <- abs(qnorm((1 - conf_level) / 2)) prop_tab <- data |> group_by({{x}}, {{y}}) |> count() |> ungroup() |> complete({{x}}, {{y}}, fill = list(n = 0)) |> group_by({{x}}) |> mutate(prop = n/sum(n)) |> ungroup() n <- prop_tab |> summarise(total_cases = sum(n)) |> purrr::pluck(1) a <- prop_tab |> group_by({{x}}) |> slice(1) |> ungroup() |> summarise(sum =abs(diff(prop))) |> purrr::pluck(1) b <- sqrt((n-1)/n) c <- prop_tab |> group_by({{y}}) |> summarise(sum = sum(n)) |> mutate(total = sum(sum)) |> mutate(fr = sum/total) |> summarise(prod = prod(fr)) |> purrr::pluck(1) d <- prop_tab |> group_by({{x}}) |> summarise(sum = sum(n)) |> mutate(num = 1) |> mutate(num/sum) |> ungroup() |> summarise(sum(num/sum)) |> purrr::pluck(1) ci <- prop_tab |> ungroup() |> rename(x = n) |> select(-prop) |> group_by(design) |> mutate(n = sum(x)) |> slice(1) |> mutate(num = x + (z^2)/4) |> mutate(den = n + (z^2)/2) |> mutate(p_adj = num/den) |> mutate(adj_n = (p_adj*(1-p_adj))/den) |> ungroup() |> mutate(lhs = diff(p_adj)) |> mutate(rhs = sum(adj_n)) |> mutate(rhs = z*sqrt(rhs)) |> mutate(upper_ci = abs(lhs) + rhs) |> mutate(lower_ci = abs(lhs) - rhs) |> slice(1) den <- sqrt(c*d) num <- a*b z <- num/den p_value <- 2*pnorm(q=z, lower.tail=FALSE) as_tibble(data.frame(a = a, b = b, c = c, d = d, den = den, num = num, z = z, p_value = p_value, n = n, lower_ci = ci$lower_ci, upper_ci = ci$upper_ci)) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_n_1_prop.R
#' T-test #' #' @param x x #' @param y y #' @param ... other arguments passed to t-test #' @return results #' @export #' @examples #' #' test_t(mtcars$mpg, mtcars$am) test_t <- function(x, y, ...) { lower_ci <- upper_ci <- X1 <- X2 <- NULL result <- stats::t.test(x, y, ...) result2 <- result$estimate |> data.frame() |> t() |> data.frame() x_name <- deparse(substitute(x)) x_name <- sub(".*\\$", "", x_name) y_name <- deparse(substitute(y)) y_name <- sub(".*\\$", "", y_name) names(result2)[1] <- x_name names(result2)[2] <- y_name ci <-result$conf.int |> t() |> data.frame() |> dplyr::rename(lower_ci = X1, upper_ci = X2) |> dplyr::mutate(lower_ci = round(lower_ci, 2), upper_ci = round(upper_ci, 2)) ci_level <- attributes(result$conf.int) |> unlist() cli::cli_h1(result$method) result2 <- result2 |> dplyr::mutate(t = round(result$statistic, 2), p = scales::pvalue(result$p.value), df = round(result$parameter), ci_level = ci_level) |> dplyr::bind_cols(tibble::tibble(ci)) |> t() |> data.frame() |> tibble::rownames_to_column(" ") |> data.frame() result2 <- result2 |> huxtable::as_hux() huxtable::position(result2) <- "left" result2 <- huxtable::map_align(result2, huxtable::by_cols("left", "right")) huxtable::print_screen(result2, colnames =FALSE) result3 <- data.frame(result2) return(invisible(result3)) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_t.R
#' Paired t-test #' #' @param x x #' @param y y #' @param ... other arguments passed to paired t-test #' @return results #' @export #' test_t_paired <- function(x, y, ...) { lower_ci <- upper_ci <- X1 <- X2 <- NULL result <- stats::t.test(x, y, paired = TRUE, ...) result2 <- result$estimate |> data.frame() |> t() |> data.frame() ci <- result$conf.int |> t() |> data.frame() |> dplyr::rename( lower_ci = X1, upper_ci = X2 ) |> dplyr::mutate( lower_ci = round(lower_ci, 2), upper_ci = round(upper_ci, 2) ) ci_level <- attributes(result$conf.int) |> unlist() cli::cli_h1(result$method) result2 <- result2 |> dplyr::mutate( t = round(result$statistic, 2), p = scales::pvalue(result$p.value), df = round(result$parameter), ci_level = ci_level ) |> dplyr::bind_cols(tibble::tibble(ci)) |> t() |> data.frame() |> tibble::rownames_to_column(" ") |> data.frame() result2 <- result2 |> huxtable::as_hux() huxtable::position(result2) <- "left" result2 <- huxtable::map_align(result2, huxtable::by_cols("left", "right")) huxtable::print_screen(result2, colnames = FALSE) result3 <- data.frame(result2) return(invisible(result3)) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_t_paired.R
#' Wald Confidence Intervals #' #' @param success success #' @param total total #' @param conf_level conf_level (default: 0.95) #' #' @return lower_ci, upper_ci #' @export #' @examples #' test_wald(10, 12, 0.95) #' test_wald(5, 7, 0.95) test_wald <- function(success, total, conf_level = 0.95) { z <- abs(qnorm((1 - conf_level) / 2)) p <- success/total value <- z*(sqrt((p*(1-p)/total))) lower_ci <- p - value upper_ci <- p + value list(lower_ci = lower_ci, upper_ci = upper_ci) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_wald.R
#' Adjusted Wald Confidence Intervals #' #' @param success success #' @param total total #' @param conf_level conf_level (default: 0.95) #' @return lower_ci, upper_ci #' @export #' @examples #' test_wald_adj(10, 12, 0.95) #' test_wald_adj(5, 7, 0.95) test_wald_adj <- function(success, total, conf_level = 0.95) { z <- abs(qnorm((1 - conf_level) / 2)) adjusted_proportion <- function(success, total, conf_level) { z <- abs(qnorm((1 - conf_level) / 2)) p_adj <- (success + z^2/2)/(total + z^2) p_adj } p_adj <- adjusted_proportion(success, total, conf_level) p <- p_adj total <- total + z*2 value <- z*(sqrt((p*(1-p)/total))) lower_ci <- p - value upper_ci <- p + value list(lower_ci = lower_ci, upper_ci = upper_ci) }
/scratch/gouwar.j/cran-all/cranData/uxr/R/test_wald_adj.R
#' Pipe operator #' #' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs #' @param lhs A value or the magrittr placeholder. #' @param rhs A function call using the magrittr semantics. #' @return The result of calling `rhs(lhs)`. NULL
/scratch/gouwar.j/cran-all/cranData/uxr/R/utils-pipe.R
#' @keywords internal "_PACKAGE" utils::globalVariables(c("pairs", "value", "type", "t.result.", "term", "adj_n", "n", "adj", 'diff2', 'value', "id", 'component', 'observed', 'expected', 'residual', 'residual_sq', 'chisq', 'prop', 'total', 'fr', 'design', 'p_adj', 'rhs', 'lhs', 'X1', 'X2', 'variables'))
/scratch/gouwar.j/cran-all/cranData/uxr/R/uxr-package.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(uxr) ## ----------------------------------------------------------------------------- data <- data.frame(task_1 = c("y", "y", "y", "y", "n", "n", "n", NA, NA, NA, NA, NA, NA, NA), task_2 = c(0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1)) ## with dataframe column benchmark_event(data, column = task_1, benchmark = 0.8, event = "y") ## ----------------------------------------------------------------------------- benchmark_event(data, column = task_2, benchmark = 0.3, event = 1, event_type = "success") ## ----------------------------------------------------------------------------- ## pipeable data |> benchmark_event(column = task_2, benchmark = 0.3, event = 1, event_type = "success") ## ----------------------------------------------------------------------------- # specify `input = "values` to use with direct values benchmark_event(benchmark = 0.8, count = 9, total = 11, input = "values") ## ----------------------------------------------------------------------------- # get confidence intervals # test_wald_adj(10, 12) ## ----------------------------------------------------------------------------- scores <- 80 + 23 * scale(rnorm(172)) # 80 = mean, 23 = sd data <- data.frame(scores = scores) ## ----------------------------------------------------------------------------- # with dataframe column benchmark_score(data, scores, 67) ## ----------------------------------------------------------------------------- # pipeable data |> benchmark_score(scores, 67) ## ----------------------------------------------------------------------------- # specify `input = "values` to use with direct values benchmark_score(mean = 80, sd = 23, n = 172, benchmark = 67, input = "values") ## ----------------------------------------------------------------------------- data <- data.frame(time = c(60, 53, 70, 42, 62, 43, 81)) benchmark_time(data, column = time, benchmark = 60, alpha = 0.05) ## ----------------------------------------------------------------------------- # Wide data - default data_wide <- data.frame(A = c(4, 2, 5, 3, 6, 2, 5), B = c(5, 2, 1, 2, 1, 3, 2)) compare_means_between_groups(data_wide, var1 = A, var2 = B) ## ----------------------------------------------------------------------------- # Long data data_long <- data_wide |> tibble::rowid_to_column("id") |> tidyr::pivot_longer(cols = -id, names_to = "group", values_to = "variable") compare_means_between_groups(data_long, variable = variable, grouping_variable = group, groups = c("A", "B"), input = "long") ## ----------------------------------------------------------------------------- A <- 51.6 + 4.07 * scale(rnorm(11)) A <- c(A, NA) B <- 49.6 + 4.63 * scale(rnorm(12)) data <- data.frame(A, B) compare_means_between_groups(data, A, B) ## ----------------------------------------------------------------------------- data <- data.frame(id = c(1:7), task1 = c(4, 1, 2, 3, 8, 4, 4), task2 = c(7, 13, 9, 7, 18, 8, 10)) compare_means_within_groups(data, task1, task2) ## ----------------------------------------------------------------------------- design = c("A","B") complete = c(10, 4) incomplete = c(2, 9) data <- data.frame(design, complete, incomplete) data <- data |> tidyr::pivot_longer(!design, names_to = "rate", values_to = "n") |> tidyr::uncount(n) compare_rates_between_groups(data, group = design, event = rate) ## ----------------------------------------------------------------------------- A <- c(1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1) B <- c(0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0) data <- data.frame(A, B) compare_rates_within_groups(data, A, B, input = "wide")
/scratch/gouwar.j/cran-all/cranData/uxr/inst/doc/examples.R
--- title: "examples" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{examples} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(uxr) ``` # Compare Probability of an Event with Benchmark ```{r} data <- data.frame(task_1 = c("y", "y", "y", "y", "n", "n", "n", NA, NA, NA, NA, NA, NA, NA), task_2 = c(0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1)) ## with dataframe column benchmark_event(data, column = task_1, benchmark = 0.8, event = "y") ``` ```{r} benchmark_event(data, column = task_2, benchmark = 0.3, event = 1, event_type = "success") ``` ```{r} ## pipeable data |> benchmark_event(column = task_2, benchmark = 0.3, event = 1, event_type = "success") ``` ```{r} # specify `input = "values` to use with direct values benchmark_event(benchmark = 0.8, count = 9, total = 11, input = "values") ``` ```{r} # get confidence intervals # test_wald_adj(10, 12) ``` # Compare Score with a Benchmark ```{r} scores <- 80 + 23 * scale(rnorm(172)) # 80 = mean, 23 = sd data <- data.frame(scores = scores) ``` ```{r} # with dataframe column benchmark_score(data, scores, 67) ``` ```{r} # pipeable data |> benchmark_score(scores, 67) ``` ```{r} # specify `input = "values` to use with direct values benchmark_score(mean = 80, sd = 23, n = 172, benchmark = 67, input = "values") ``` # Compare Time with a Benchmark ```{r} data <- data.frame(time = c(60, 53, 70, 42, 62, 43, 81)) benchmark_time(data, column = time, benchmark = 60, alpha = 0.05) ``` # Compare Means Between Groups ```{r} # Wide data - default data_wide <- data.frame(A = c(4, 2, 5, 3, 6, 2, 5), B = c(5, 2, 1, 2, 1, 3, 2)) compare_means_between_groups(data_wide, var1 = A, var2 = B) ``` ```{r} # Long data data_long <- data_wide |> tibble::rowid_to_column("id") |> tidyr::pivot_longer(cols = -id, names_to = "group", values_to = "variable") compare_means_between_groups(data_long, variable = variable, grouping_variable = group, groups = c("A", "B"), input = "long") ``` ```{r} A <- 51.6 + 4.07 * scale(rnorm(11)) A <- c(A, NA) B <- 49.6 + 4.63 * scale(rnorm(12)) data <- data.frame(A, B) compare_means_between_groups(data, A, B) ``` # Compare Means Within Groups ```{r} data <- data.frame(id = c(1:7), task1 = c(4, 1, 2, 3, 8, 4, 4), task2 = c(7, 13, 9, 7, 18, 8, 10)) compare_means_within_groups(data, task1, task2) ``` # Compare Rates Between Groups ```{r} design = c("A","B") complete = c(10, 4) incomplete = c(2, 9) data <- data.frame(design, complete, incomplete) data <- data |> tidyr::pivot_longer(!design, names_to = "rate", values_to = "n") |> tidyr::uncount(n) compare_rates_between_groups(data, group = design, event = rate) ``` # Compare Rates Within Groups ```{r} A <- c(1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1) B <- c(0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0) data <- data.frame(A, B) compare_rates_within_groups(data, A, B, input = "wide") ```
/scratch/gouwar.j/cran-all/cranData/uxr/inst/doc/examples.Rmd
--- title: "examples" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{examples} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(uxr) ``` # Compare Probability of an Event with Benchmark ```{r} data <- data.frame(task_1 = c("y", "y", "y", "y", "n", "n", "n", NA, NA, NA, NA, NA, NA, NA), task_2 = c(0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1)) ## with dataframe column benchmark_event(data, column = task_1, benchmark = 0.8, event = "y") ``` ```{r} benchmark_event(data, column = task_2, benchmark = 0.3, event = 1, event_type = "success") ``` ```{r} ## pipeable data |> benchmark_event(column = task_2, benchmark = 0.3, event = 1, event_type = "success") ``` ```{r} # specify `input = "values` to use with direct values benchmark_event(benchmark = 0.8, count = 9, total = 11, input = "values") ``` ```{r} # get confidence intervals # test_wald_adj(10, 12) ``` # Compare Score with a Benchmark ```{r} scores <- 80 + 23 * scale(rnorm(172)) # 80 = mean, 23 = sd data <- data.frame(scores = scores) ``` ```{r} # with dataframe column benchmark_score(data, scores, 67) ``` ```{r} # pipeable data |> benchmark_score(scores, 67) ``` ```{r} # specify `input = "values` to use with direct values benchmark_score(mean = 80, sd = 23, n = 172, benchmark = 67, input = "values") ``` # Compare Time with a Benchmark ```{r} data <- data.frame(time = c(60, 53, 70, 42, 62, 43, 81)) benchmark_time(data, column = time, benchmark = 60, alpha = 0.05) ``` # Compare Means Between Groups ```{r} # Wide data - default data_wide <- data.frame(A = c(4, 2, 5, 3, 6, 2, 5), B = c(5, 2, 1, 2, 1, 3, 2)) compare_means_between_groups(data_wide, var1 = A, var2 = B) ``` ```{r} # Long data data_long <- data_wide |> tibble::rowid_to_column("id") |> tidyr::pivot_longer(cols = -id, names_to = "group", values_to = "variable") compare_means_between_groups(data_long, variable = variable, grouping_variable = group, groups = c("A", "B"), input = "long") ``` ```{r} A <- 51.6 + 4.07 * scale(rnorm(11)) A <- c(A, NA) B <- 49.6 + 4.63 * scale(rnorm(12)) data <- data.frame(A, B) compare_means_between_groups(data, A, B) ``` # Compare Means Within Groups ```{r} data <- data.frame(id = c(1:7), task1 = c(4, 1, 2, 3, 8, 4, 4), task2 = c(7, 13, 9, 7, 18, 8, 10)) compare_means_within_groups(data, task1, task2) ``` # Compare Rates Between Groups ```{r} design = c("A","B") complete = c(10, 4) incomplete = c(2, 9) data <- data.frame(design, complete, incomplete) data <- data |> tidyr::pivot_longer(!design, names_to = "rate", values_to = "n") |> tidyr::uncount(n) compare_rates_between_groups(data, group = design, event = rate) ``` # Compare Rates Within Groups ```{r} A <- c(1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1) B <- c(0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0) data <- data.frame(A, B) compare_rates_within_groups(data, A, B, input = "wide") ```
/scratch/gouwar.j/cran-all/cranData/uxr/vignettes/examples.Rmd
#' @keywords internal "_PACKAGE" ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/DiveR-package.R
#' k-mer sequences concatenation #' #' This function concatenates completely (index incidence = 100%)/highly (90% <= #' index incidence < 100%) conserved k-mer positions that overlapped at least one #' k-mer position or are adjacent to each other and generate the CCS/HCS sequence #' in either CSv or FASTA format #' #' @param data DiMA JSON converted csv file data #' @param conservation_level CCS (completely conserved) / HCS (highly conserved) #' @param kmer size of the k-mer window #' @param threshold_pct manually set threshold of index.incidence for HCS #' @return A list wit csv and fasta dataframes #' @examples csv<-concat_conserved_kmer(proteins_1host)$csv #' @examples csv_2hosts<-concat_conserved_kmer(protein_2hosts, conservation_level = "CCS")$csv #' @examples fasta <- concat_conserved_kmer(protein_2hosts, conservation_level = "HCS")$fasta #' @importFrom magrittr %>% #' @importFrom dplyr filter select summarise group_by slice bind_rows mutate n #' @importFrom stringr str_sub #' @importFrom tidyr spread separate #' @importFrom rlang := #' @export concat_conserved_kmer <- function(data, conservation_level = "HCS", kmer=9, threshold_pct = NULL){ index.incidence <- proteinName <- indexSequence <- n <- start <- end <- NULL # threshold HCS / CCS if (is.null(threshold_pct)) { threshold <- ifelse(conservation_level == "CCS", 100, 90) } else { message(sprintf("Manually selected threshold for HCS: %s", threshold_pct)) threshold <- threshold_pct } # filter whole dataset by index.incidence (HCS/CCS) df <- data %>% dplyr::filter(index.incidence >= threshold) # # stop if no peptides were found # if (nrow(df) == 0) { # # stop("No sequences with a given conservation level were found", call.=FALSE) # message("No sequences with a given conservation level were found") # return() # } # ---- 1. Protein Sequences ---- # remember whole sequence of the protein proteins_seq <- data %>% dplyr::select(proteinName, indexSequence) %>% dplyr::group_by(proteinName) %>% dplyr::summarise(seq = paste0(str_sub(indexSequence, 1, 1), collapse = "")) %>% tidyr::spread(key = proteinName, value = seq) # add missing last amino acids for (protein in unique(data$proteinName)) { proteins_seq[[protein]] <- paste0(proteins_seq[[protein]], data %>% dplyr::filter(proteinName == protein) %>% dplyr::select(indexSequence) %>% dplyr::slice(n()) %>% as.character() %>% stringr::str_sub(2)) } # ---- 2. Dataset manipulations ---- # first split by protein name # then separately proceed with each table (each protein independently) # then rbind csv_df <- bind_rows( lapply(split(df, df$proteinName), function(df_x) { # remember protein name prot_name <- df_x[1, "proteinName", drop = TRUE] # create table of all indexes falling into peptides (from filtered df) # cols: indexes of all amino acids # rows: peptides # value: TRUE for all amino acids from peptide on their indexes # example: row VKRP (from 22 to 25) - cols 22-25 will have TRUE index <- bind_rows( apply(df_x, 1, function(row) { start_pos <- as.numeric(row["position"]) data.frame(matrix(data = TRUE, nrow = 1, ncol = kmer, dimnames = list(row["indexSequence"], seq(start_pos, start_pos + kmer - 1)))) }) ) %>% # if for any index there is amino acid from conservative peptide - set TRUE apply(2, any) %>% names() %>% as.data.frame() %>% # get rid of "X" in front of indexes tidyr::separate(col = 1, into = c("x", "index"), sep = 1) %>% dplyr::mutate(index = as.integer(index)) %>% dplyr::select(index) # set start and end indexes for each consecutive index series # calculated as difference between previous and next elements # diff = 1 means that sequence still continuing # diff > 1 means that there was a gap -> next sequence started # example: 4-5-6-10-11-12 // diff = 1-1-4-1-1 # sequences: 4-6 (ind.1-3), 10-12 (ind.4-6) start_ind <- index$index[c(1, which(diff(index$index) > 1) + 1)] end_ind <- index$index[c(which(diff(index$index) > 1), length(index$index))] # format columns for output index_df <- data.frame( n = seq(length(start_ind)), start = start_ind, end = end_ind ) %>% dplyr::mutate( !!conservation_level := sprintf("%s_%s_%i", conservation_level, prot_name, n), Position = sprintf("%i-%i", start, end), Sequence = str_sub(proteins_seq[[prot_name]], start, end) ) %>% dplyr::select(-c(n, start, end)) }) ) if (nrow(csv_df) == 0) { cons_lvl <- ifelse(conservation_level == "HCS", "highly conserved", "completely conserved") message_df <- data.frame( Warning_message = c(sprintf("No %s sequences were found!", cons_lvl))) message(sprintf("No %s sequences were found!", cons_lvl)) return(list(csv=message_df, fasta=message_df)) } # create df to store info for fasta file fasta_df <- do.call(rbind, lapply(seq(nrow(csv_df)), function(i) { csv_df[i, ] %>% dplyr::select(-Position) %>% dplyr::mutate(!!conservation_level := paste0(">", get(conservation_level))) %>% t() })) return(list(csv=csv_df, fasta=fasta_df)) }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/concat_conserved_kmer.R
#' JSON2CSV #' #' This function converts DiMA (v4.1.1) JSON output file to a dataframe with 17 #' predefined columns which further acts as the input for other functions provided in this vDiveR package. #' #' @param json_data DiMA JSON output dataframe #' @param host_name name of the host species #' @param protein_name name of the protein #' @return A dataframe which acts as input for the other functions in vDiveR package #' @examples inputdf<-json2csv(JSON_sample) #' @importFrom stats aggregate #' @importFrom dplyr mutate_if right_join distinct #' @importFrom tidyr replace_na #' @export json2csv <-function(json_data, host_name="unknown host", protein_name="unknown protein"){ Group.2 <- x <- results.position <- results.diversity_motifs <- motif_short <- NULL data_flatten <- as.data.frame(json_data) %>% tidyr::unnest(cols = c(results.diversity_motifs)) # data transformation motifs_incidence <- aggregate(data_flatten$incidence, list(data_flatten$results.position,data_flatten$motif_short), FUN=sum) %>% tidyr::spread(Group.2,x) %>% # transpose the rows (motif-long & incidence) to columns (index, major, minor, unique) dplyr::mutate_if(is.numeric, ~(replace_na(., 0))) # replace NAN with 0 #rename column 'Group.1' to 'results.position' colnames(motifs_incidence)[colnames(motifs_incidence) == 'Group.1'] <- "results.position" #sum the number of Index motif found in each position (if > 1 => multiIndex == TRUE) multiIndex<-data_flatten%>% group_by(results.position) %>% dplyr::summarize(multiIndex = sum(motif_short=="I")) %>% as.data.frame() #merge multiIndex to motifs_incidence df motifs_incidence <-right_join(motifs_incidence,multiIndex, by='results.position')%>% distinct() #replace multiIndex with boolean: x > 1 = TRUE and vice versa motifs_incidence$multiIndex <- ifelse(motifs_incidence$multiIndex>1, TRUE,FALSE) #extract the first encountered index kmer info if > 1 index is encountered for each position (rarely happens) index_data<-subset(data_flatten, motif_short == "I") %>% #extract rows that are of index group_by(results.position) %>% #group them based on position slice(1) %>% #take the first index encountered per position as.data.frame() #return the data in dataframe #replace low_support of NAN to FALSE index_data$results.low_support[is.na(index_data$results.low_support)] <- FALSE #combine both the index and variant motif information to motifs motifs<-right_join(motifs_incidence,index_data[c('query_name',"results.support","results.low_support","results.entropy","results.distinct_variants_incidence","results.position","results.total_variants_incidence","sequence",'highest_entropy.position','highest_entropy.entropy','average_entropy')],by='results.position')%>% distinct() #assign host motifs['host'] <- host_name #check if all expected columns are present #assert column with value of 0 if absent expected_columns<-c('results.position','I','Ma','Mi','U','multiIndex','query_name','results.support','results.low_support','results.entropy','results.distinct_variants_incidence','results.total_variants_incidence','sequence','highest_entropy.position','highest_entropy.entropy','average_entropy','host') missing_columns <- dplyr::setdiff(expected_columns, colnames(motifs)) template <- data.frame(matrix(0, nrow = nrow(motifs), ncol = length(missing_columns))) # Create a template dataframe with missing columns filled with 0 colnames(template) <- missing_columns motifs <- cbind(motifs, template) # Combine the template dataframe and the original motifs dataframe motifs <- motifs[, expected_columns] # Reorder columns to match the expected order #rename columns colnames(motifs)<-c('position','index.incidence','major.incidence','minor.incidence','unique.incidence','multiIndex','proteinName','count','lowSupport','entropy','distinctVariant.incidence','totalVariants.incidence','indexSequence','highestEntropy.position','highestEntropy','averageEntropy','host') #reorder the columns motifs<-motifs[,c(7,1,8,9,10,13,2,3,4,5,12,11,6,17,14,15,16)] motifs }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/json2csv.R
#' Metadata Extraction from NCBI/GISAID EpiCoV FASTA file #' #' This function retrieves metadata (ID, country, date) from the NCBI/GISAID EpiCoV FASTA file (default FASTA header expected). #' #' @param file_path path of fasta file #' @param source the source of fasta file, either "ncbi" or "GISAID" #' @return A dataframe that has three columns consisting ID, collected country and collected date #' @examples filepath <- system.file('extdata','GISAID_EpiCoV.faa', package = 'vDiveR') #' @examples meta_gisaid <- metadata_extraction(filepath, 'GISAID') #' @export metadata_extraction <- function(file_path, source){ if(source == 'ncbi'){ meta <- extract_from_NCBI(file_path) } if(source == 'GISAID'){ meta <- extract_from_GISAID(file_path) } return(meta) } #' Extract metadata via fasta file from GISAID #' #' This function get the metadata from each header of GISAID fasta file #' @param file_path path of fasta file #' @importFrom stringr str_extract extract_from_GISAID <- function(file_path){ heads <- c() lines <- readLines(file_path, warn=FALSE) for(line in lines){ if(grepl('>', line)){ line <- substr(line, 2, nchar(line)) heads <- c(heads, line) } } IDs <- c(); countries <- c(); dates <- c() for(head in heads){ ID <- str_extract(head, "EPI[^|]*"); IDs <- c(IDs, ID) country <- tryCatch(strsplit(head, '/', fixed=T)[[1]][2], error = function(e) "NA") countries <- c(countries, country) date <- str_extract(head, "[0-9]{4}-[0-9]{2}-[0-9]{2}"); dates <- c(dates, date) } return(data.frame('ID' = IDs, 'country' = countries, 'date' = dates)) } #' Extract metadata via fasta file from ncbi #' #' This function get the metadata from each head of fasta file #' @param file_path path of fasta file #' @importFrom rentrez entrez_search entrez_fetch extract_from_NCBI <- function(file_path){ IDs <- c() lines <- readLines(file_path, warn=FALSE) for(line in lines){ if(grepl('>', line)){ ID <- strsplit(line, ' ')[[1]][1] ID <- substr(ID,2,nchar(ID)) IDs <- c(IDs, ID) } } countries <- c(); dates <- c(); dropsample <- c(); keepsample <- c() for(ID in IDs){ if(substr(ID,1,3) == 'pdb'){ dropsample <- c(dropsample, ID) next } keepsample <- c(keepsample, ID) search_result <- entrez_search(db = "protein", term = ID, retmax = 1) accession <- search_result$ids[[1]] info <- entrez_fetch(db = "protein", id = accession, rettype = "gb", retmode = "text") info <- tryCatch(strsplit(info, '\n')[[1]], error = function(e) "") idx1 <- grep('/country=', info); idx2 <- grep('/collection_date=', info) info1 <- info[idx1]; info2 <- info[idx2] country <- tryCatch(strsplit(info1, '\\"')[[1]][2], error = function(e) "NA") if (grepl(':', country)) { country <- strsplit(country,':')[[1]][1] } date <- tryCatch(strsplit(info2, '\\"')[[1]][2], error = function(e) "NA") countries <- c(countries, country); dates <- c(dates, date) } tmp <- data.frame('ID' = keepsample, 'country' = countries, 'date' = dates) for(i in 1:nrow(tmp)){ if(!is.na(as.Date(tmp$date[i],format='%Y-%m-%d'))){ tt <- 1 } else if(!is.na(as.Date(tmp$date[i],format='%d-%B-%Y'))){ tmp$date[i] <- as.character(as.Date(tmp$date[i],format="%d-%B-%Y")) } else { dropsample <- c(dropsample, tmp$ID[i]) } } warninfo <- paste(c('\nExcluded records:\n',dropsample, '\nCountry/date (%Y-%m-%d OR %d-%B-%Y format) are not provided.'), collapse = " ") warning(warninfo) tmp <- tmp[! tmp$ID %in% dropsample, ] return(tmp) }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/metadata_extraction.R
#' Conservation Levels Distribution Plot #' #' This function plots conservation levels distribution of k-mer positions, which consists of #' completely conserved (black) (index incidence = 100\%), highly conserved (blue) #' (90\% <= index incidence < 100\%), mixed variable (green) (20\% < index incidence <= 90\%), #' highly diverse (purple) (10\% < index incidence <= 20\%) and #' extremely diverse (pink) (index incidence <= 10\%). #' #' @param df DiMA JSON converted csv file data #' @param protein_order order of proteins displayed in plot #' @param conservation_label 0 (partial; show present conservation labels only) or 1 (full; show ALL conservation labels) in plot #' @param host number of host (1/2) #' @param base_size base font size in plot #' @param line_dot_size lines and dots size #' @param label_size conservation labels font size #' @param alpha any number from 0 (transparent) to 1 (opaque) #' @examples plot_conservationLevel(proteins_1host, conservation_label = 1,alpha=0.8, base_size = 15) #' @examples plot_conservationLevel(protein_2hosts, conservation_label = 0, host=2) #' @return A plot #' @importFrom dplyr case_when #' @importFrom grid unit #' @importFrom gridExtra grid.arrange #' @export plot_conservationLevel <- function(df, protein_order="", conservation_label=1, host=1, base_size = 11, line_dot_size = 2, label_size = 2.6, alpha=0.6){ df <- df %>% data.frame() %>% mutate( ConservationLevel = case_when( df$index.incidence == 100 ~ "Completely conserved (CC)", df$index.incidence >= 90 ~ "Highly conserved (HC)", df$index.incidence >= 20 ~ "Mixed variable (MV)", df$index.incidence >= 10 ~ "Highly diverse (HD)", df$index.incidence < 10 ~ "Extremely diverse (ED)" ) ) #single host if (host == 1){ plot_plot7(data = df,protein_order = protein_order,conservation_label = conservation_label, base_size = base_size, label_size = label_size) }else{ #multihost #split the data into multiple subsets (if multiple hosts detected) plot7_list<-split(df,df$host) plot7_multihost<-lapply(plot7_list,plot_plot7, protein_order,conservation_label, base_size, label_size) #create spacing between multihost plots theme = theme(plot.margin = unit(c(2.5,1.0,0.1,0.5), "cm")) do.call("grid.arrange", c(grobs=lapply(plot7_multihost,"+",theme), nrow = length(unique(df$host)))) } } #' @importFrom plyr ddply . #' @importFrom ggplot2 position_jitter scale_colour_manual #' @importFrom ggplot2 position_dodge coord_cartesian #' @importFrom gghalves geom_half_boxplot geom_half_point #' @importFrom ggtext geom_richtext #plotting function plot_plot7<- function(data, protein_order="", conservation_label=1, base_size = 11, line_dot_size = 2, label_size = 2.6, alpha =0.6){ proteinName <- Total <- index.incidence <- NULL Label <- ConservationLevel <- NULL #add word 'protein' in front of each protein name data$proteinName<-paste("Protein",data$proteinName) #create data for proteome bar "All" from existing data data1<-data data1$proteinName <- "All" data1$level <- "All" #set up the order of proteins in plot from left to right if (protein_order ==""){ #follow the default order in csv file level<-c("All",unique(data$proteinName)) }else{ #order the proteins based on user input level<-c("All",strsplit(protein_order, ',')[[1]]) } #determine the protein order data$level = factor(data$proteinName, levels=level) #combine proteome bar with protein bars data<-rbind(data1,data) #determine the protein order data$level = factor(data$proteinName, levels=level) #calculation for total and percentage of conservation levels for each protein #sum up the total positions for each conservation level of proteins plot7_data<-ddply(data,.(proteinName,ConservationLevel),nrow) names(plot7_data)[3]<-"Total" C_level<- c("Completely conserved (CC)", "Highly conserved (HC)", "Mixed variable (MV)", "Highly diverse (HD)", "Extremely diverse (ED)") #check the presence of conservation level: insert value 0 if it is absent if (conservation_label == 1){ #full label #check the presence of conservation level: insert value 0 if it is absent for ( conservation in C_level){ #conservation level for (name in level){ #proteinName if (!(conservation %in% plot7_data[plot7_data$proteinName==name,]$ConservationLevel)){ plot7_data<-rbind(plot7_data,c(name,conservation,0)) }}} } #sort the dataframe plot7_data[order(plot7_data$proteinName),] plot7_data$Total<- as.integer(plot7_data$Total) #get the percentage of each conservation level for each protein plot7_data<-ddply(plot7_data,.(proteinName),transform, percent=Total/sum(Total)*100) #gather the protein label in multicolor plot7_data<-plot7_data%>%mutate(Label = case_when( plot7_data$ConservationLevel == "Completely conserved (CC)" ~ paste0(sprintf("<span style = 'color:#000000;'>CC: %.0f (%.1f %%) </span>",plot7_data$Total, round(plot7_data$percent,1))), plot7_data$ConservationLevel == "Highly conserved (HC)" ~ paste0(sprintf("<span style = 'color:#0057d1;'>HC: %.0f (%.1f %%) </span>",plot7_data$Total, round(plot7_data$percent,1))), plot7_data$ConservationLevel == "Mixed variable (MV)" ~ paste0(sprintf("<span style = 'color:#02d57f;'>MV: %.0f (%.1f %%) </span>",plot7_data$Total, round(plot7_data$percent,1))), plot7_data$ConservationLevel == "Highly diverse (HD)" ~ paste0(sprintf("<span style = 'color:#A022FF;'>HD: %.0f (%.1f %%) </span>",plot7_data$Total, round(plot7_data$percent,1))), plot7_data$ConservationLevel == "Extremely diverse (ED)" ~ paste0(sprintf("<span style = 'color:#ff617d;'>ED: %.0f (%.1f %%) </span>",plot7_data$Total, round(plot7_data$percent,1))), )) #set conservation level in specific order (CC,HC,MV,HD,ED) plot7_data<-plot7_data[order(factor(plot7_data$ConservationLevel, levels=c("Completely conserved (CC)", "Highly conserved (HC)", "Mixed variable (MV)", "Highly diverse (HD)", "Extremely diverse (ED)"))),] #combine all conservation level labels into one for each protein Proteinlabel<- aggregate(Label~proteinName, plot7_data, paste, collapse="<br>") #get number of protein for labelling nProtein<-nrow(Proteinlabel) #plotting ggplot(data, aes(x=level,y=index.incidence)) + # gghalfves geom_half_boxplot(outlier.shape = NA) + geom_half_point(aes(col = ConservationLevel), side = "r", position = position_jitter(width = 0, height=-0.7), size=line_dot_size, alpha=alpha) + ylim(0,105) + labs(x=NULL, y="Index incidence (%)\n", fill="Conservation level")+ theme_classic(base_size = base_size)+ theme( legend.key = element_rect(fill = "transparent", colour = "transparent"), legend.position = 'bottom', plot.margin = unit(c(5, 1, 1, 1), "lines"), axis.ticks.x = element_blank(), axis.text.x = element_text(angle = 55, vjust = 0.5, hjust=0.5) ) + scale_colour_manual('Conservation Level', breaks = c("Completely conserved (CC)", "Highly conserved (HC)", "Mixed variable (MV)", "Highly diverse (HD)", "Extremely diverse (ED)"), values = c("Completely conserved (CC)"="black", "Highly conserved (HC)"="#0057d1", "Mixed variable (MV)"="#02d57f", "Highly diverse (HD)"="#8722ff", "Extremely diverse (ED)"="#ff617d")) + geom_richtext(data = Proteinlabel, aes(x=proteinName,label = Label, y=c(rep(105,nProtein)), label.size=0, label.color="transparent"), position = position_dodge(width=0.1), size=label_size, color="black", hjust=0, angle=90) + guides(color = guide_legend(override.aes = list(size = 2), nrow=2))+ coord_cartesian(clip = "off")+ #allow ggtext outside of the plot ggtitle(unique(data$host)) }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/plot_conservationLevel.R
#' Entropy and total variant incidence correlation plot #' #' This function plots the correlation between entropy and total variant incidence #' of all the provided protein(s). #' #' @param df DiMA JSON converted csv file data #' @param host number of host (1/2) #' @param alpha any number from 0 (transparent) to 1 (opaque) #' @param line_dot_size dot size in scatter plot #' @param ylabel y-axis label #' @param xlabel x-axis label #' @param ymax maximum y-axis #' @param ybreak y-axis breaks #' @param base_size base font size in plot #' @examples plot_correlation(proteins_1host) #' @examples plot_correlation(protein_2hosts, base_size = 2, ybreak=1, ymax=10, host = 2) #' @return A scatter plot #' @importFrom ggplot2 ggplot geom_point aes labs scale_x_continuous scale_y_continuous theme_classic theme element_rect facet_grid #' @importFrom grid unit #' @importFrom dplyr vars #' @export plot_correlation <- function(df, host = 1 , alpha = 1/3, line_dot_size = 3, base_size = 11, ylabel = "k-mer entropy (bits)\n", xlabel = "\nTotal variants (%)", ymax = ceiling(max(df$entropy)), ybreak=0.5){ totalVariants.incidence <- entropy <- NULL plot2<-ggplot(df)+geom_point(mapping = aes(x=totalVariants.incidence,y=entropy),alpha=alpha,size=line_dot_size)+ labs(y = ylabel,x= xlabel)+ scale_x_continuous(limits = c(0, 100), breaks = seq(0, 100, 20))+ scale_y_continuous(limits = c(0, ymax), breaks = seq(0, ymax, ybreak))+ theme_classic(base_size = base_size)+ theme( panel.border = element_rect(colour = "#000000", fill=NA, size=1) ) if (host == 1){ #single host #plot the scatter plot with density plot2 }else{ #multiple host plot2+facet_grid(rows = vars(df$host),space = "free",switch = "x") } }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/plot_correlation.R
#' Dynamics of Diversity Motifs (Protein) Plot #' #' This function compactly display the dynamics of diversity motifs (index and its variants: major, minor and unique) #' in the form of dot plot(s) as well as violin plots for all the provided individual protein(s). #' #' @param df DiMA JSON converted csv file data #' @param host number of host (1/2) #' @param protein_order order of proteins displayed in plot #' @param base_size base font size in plot #' @param alpha any number from 0 (transparent) to 1 (opaque) #' @param line_dot_size dot size in scatter plot #' @param bw smoothing bandwidth of violin plot (default: nrd0) #' @param adjust adjust the width of violin plot (default: 1) #' @return A plot #' @examples plot_dynamics_protein(proteins_1host) #' @importFrom gridExtra grid.arrange #' @export plot_dynamics_protein<-function(df, host=1, protein_order="", base_size=8, alpha = 1/3, line_dot_size = 3, bw = "nrd0", adjust = 1){ #single host if (host == 1){ plot4_5(data=df, protein_order=protein_order, base_size=base_size,alpha=alpha, line_dot_size=line_dot_size, bw = bw, adjust = adjust) }else{ #multihost #split the data into multiple subsets (if multiple hosts detected) plot4_list<-split(df,df$host) plot4_multihost<-lapply(plot4_list,plot4_5,protein_order, alpha, line_dot_size, base_size, host, bw, adjust) #create spacing between multihost plots theme = theme(plot.margin = unit(c(0.5,1.0,0.1,0.5), "cm")) do.call("grid.arrange", c(grobs=lapply(plot4_multihost,"+",theme), ncol = length(unique(df$host)))) } } #' @importFrom ggplot2 guides guide_legend scale_colour_manual ggtitle element_text #' @importFrom ggplot2 geom_violin geom_boxplot ylim scale_color_grey margin element_line #' @importFrom ggplot2 scale_fill_manual theme_bw facet_grid xlab ylab #' @importFrom ggpubr annotate_figure ggarrange text_grob plot4_5<-function(data, protein_order="",alpha=1/3, line_dot_size=3, base_size=8, host=1, bw = "nrd0", adjust = 1){ Total_Variants <- Incidence <- Group <- x <- proteinName <- entropy <- NULL plot4_data<-data.frame() group_names<-c("Index", "Major","Minor", "Unique", "Total variants","Distinct variants") for (i in 7:12){ tmp<-data.frame(proteinName=data[1],position=data[2],incidence=data[i],total_variants=data[11],Group=group_names[i-6],Multiindex=data[13]) #multiple host if (host != 1) { tmp$host = data[14] } names(tmp)[3]<-"Incidence" names(tmp)[4]<-"Total_Variants" plot4_data<-rbind(plot4_data,tmp) } if (protein_order !=""){ #order the proteins based on user input level<-strsplit(protein_order, ',')[[1]] #set protein order as factor plot4_data$proteinName<-factor(plot4_data$proteinName, levels=level) plot4_data$size_f = factor(plot4_data$proteinName,levels = level) } plot5_data<-plot4_data #plot plot 4 plot4<-ggplot()+geom_point(plot4_data,mapping=aes(x=Total_Variants,y=Incidence,color=Group),alpha=alpha,size=line_dot_size)+ scale_x_continuous(limits = c(0, 100), breaks = seq(0, 100, 20))+ scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 20))+ labs(y = "Incidence (%)",x= NULL)+ theme_classic(base_size = base_size)+ theme( legend.background = element_rect(fill = "transparent"), panel.border = element_rect(colour = "black", fill=NA, size=1), legend.position = "bottom" )+ guides(colour = guide_legend(override.aes = list(alpha = 1,size=2),keywidth = 1,keyheight = 1,nrow=1,byrow=TRUE))+ scale_colour_manual('',values = c("Index"="black","Total variants"="#f7238a", "Major"="#37AFAF","Minor"="#42aaff","Unique"="#af10f1","Distinct variants"="#c2c7cb" )) plot4<-plot4+facet_grid(cols=vars(plot4_data$proteinName)) #host label if("host" %in% colnames(data)){ plot4<-plot4+ggtitle(unique(data$host))+ theme(plot.title = element_text(hjust = 0.5)) } if (length(unique(data$proteinName)) <=10){ #prepare the data for each subplot of plot5 index<-plot5_data[plot5_data$Group %in% c("Index"),] major<-plot5_data[plot5_data$Group %in% c("Major"),] minor<-plot5_data[plot5_data$Group %in% c("Minor"),] unique<-plot5_data[plot5_data$Group %in% c("Unique"),] nonatypes<-plot5_data[plot5_data$Group %in% c("Distinct variants"),] variants_max_yaxis<-ceiling((max(as.numeric(major$Incidence),as.numeric(minor$Incidence),as.numeric(unique$Incidence))/10))*10 #plot 5 plot5_index<-ggplot(index, aes(x=proteinName, y=Incidence))+ geom_violin(fill="black",trim = TRUE, color="black",alpha=0.9, adjust=adjust, bw=bw)+ylim(0,100)+ylab("Index k-mer (%)")+xlab("") +theme_bw() + geom_boxplot(outlier.shape = NA,width=0.05, color="white",alpha=0.15,fill="white")+ theme_classic(base_size = base_size)+ theme(plot.margin = unit(c(0,0.1,0,0.1), "cm"), panel.border = element_rect(colour = "black", fill=NA, size=1), axis.ticks.x = element_blank()) plot5_tv<-ggplot(index, aes(x=proteinName, y=Total_Variants))+ geom_violin(fill="#f7238a",trim = TRUE, color="#f7238a",alpha=0.9, adjust=adjust, bw=bw)+ylim(0,100)+ylab("Total variant (%)")+xlab("") +theme_bw() + geom_boxplot(outlier.shape = NA,width=0.05, color="black",alpha=0.15,fill="white")+ theme_classic(base_size = base_size)+ theme(plot.margin = unit(c(0,0.1,0.1,0.1), "cm"), panel.border = element_rect(colour = "black", fill=NA, size=1), axis.ticks.x = element_blank()) plot5_major<-ggplot(major, aes(x=proteinName, y=Incidence)) + geom_violin(fill="#37AFAF",trim = TRUE, color="#37AFAF", adjust=adjust, bw=bw)+ylim(0,variants_max_yaxis)+ylab("Major variant (%)")+xlab("")+theme_bw() + geom_boxplot(outlier.shape = NA,width=0.04, color="black", alpha=0.15,fill="white")+ theme_classic(base_size = base_size)+ theme(plot.margin = unit(c(0,0.1,0,0.1), "cm"), panel.border = element_rect(colour = "black", fill=NA, size=1), axis.ticks.x = element_blank(), axis.text.y = element_text(face="bold")) plot5_minor<-ggplot(minor, aes(x=proteinName, y=Incidence))+ geom_violin(fill="#42aaff",trim = TRUE,color="#42aaff", adjust=adjust, bw=bw)+ylim(0,variants_max_yaxis)+ylab("Minor variants (%)")+xlab("") +theme_bw() + geom_boxplot(outlier.shape = NA,width=0.04, color="black", alpha=0.15,fill="white")+ theme_classic(base_size = base_size)+ theme(plot.margin = unit(c(0,0.1,0,0.1), "cm"), panel.border = element_rect(colour = "black", fill=NA, size=1), axis.ticks.x = element_blank(), axis.text.y = element_text(face="bold")) plot5_unique<-ggplot(unique, aes(x=proteinName, y=Incidence)) + geom_violin(fill="#af10f1",trim = TRUE, color="#af10f1", adjust=adjust, bw=bw)+ylim(0,variants_max_yaxis)+ylab("Unique variants (%)")+xlab("")+theme_bw() + geom_boxplot(outlier.shape = NA,width=0.05, color="black", alpha=0.15,fill="white")+ theme_classic(base_size = base_size)+ theme(plot.margin = unit(c(0,0.1,0,0.1), "cm"), panel.border = element_rect(colour = "black", fill=NA, size=1), axis.ticks.x = element_blank(), axis.text.y = element_text(face="bold")) plot5_nonatypes<-ggplot(nonatypes, aes(x=proteinName, y=Incidence)) + geom_violin(fill="#c2c7cb",trim = TRUE, color="#c2c7cb", adjust=adjust, bw=bw)+ylim(0,100)+ylab("Distinct variants (%)")+xlab("")+theme_bw()+ geom_boxplot(outlier.shape = NA,width=0.05, color="black", alpha=0.15,fill="white") + theme_classic(base_size = base_size)+ theme(plot.margin = unit(c(0,0.1,0,0.1), "cm"), panel.border = element_rect(colour = "black", fill=NA, size=1), axis.line.x = element_line(size = 0.5, linetype = "solid", colour = "black"), axis.ticks.x = element_blank()) plot5<-ggarrange(plot5_index,plot5_tv,plot5_nonatypes,plot5_major,plot5_minor,plot5_unique,ncol=3,nrow=2) } else { plot5_data$Group[plot5_data$Group == "Index"] <- "Index k-mer" plot5_data$Group[plot5_data$Group == "Major"] <- "Major variant" plot5_data$Group[plot5_data$Group == "Minor"] <- "Minor variants" plot5_data$Group[plot5_data$Group == "Unique"] <- "Unique variants" plot5_data$Group<-factor(plot5_data$Group, levels=c("Index k-mer","Total variants", "Distinct variants", "Major variant", "Minor variants", "Unique variants")) variants<-subset(plot5_data, Group=="Major variant" | Group=="Minor variants" | Group=="Unique variants") max_ylim<-ceiling((max(variants$Incidence)/10))*10 # scales_y <- list( # "Index k-mer" = scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 20)), # "Total variants" = scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 20)), # "Distinct variants" = scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 20)), # "Major variant" = scale_y_continuous(limits = c(0, max_ylim), breaks = seq(0, max_ylim, 10)), # "Minor variants" = scale_y_continuous(limits = c(0, max_ylim), breaks = seq(0, max_ylim, 10)), # "Unique variants" = scale_y_continuous(limits = c(0, max_ylim), breaks = seq(0, max_ylim, 10)) # ) breaks_fun <- function(x) { if (max(x)<= max_ylim){ seq(0,max_ylim,10) }else{ seq(0,100,20) } } limits_fun <- function(x) { if (max(x)<= max_ylim){ c(0,max_ylim) }else{ c(0,100) } } plot5<-ggplot()+ geom_violin(data=plot5_data,aes(x=proteinName,y=Incidence, fill=Group, color=Group), trim=TRUE, adjust=adjust, bw=bw)+ theme_classic(base_size = base_size)+xlab("Protein")+ylab("Incidence (%)\n")+ theme(panel.border = element_rect(colour = "black", fill=NA, size=1), legend.position="none")+ scale_y_continuous(limits = limits_fun,breaks = breaks_fun)+ facet_grid(rows = vars(Group),switch="y",scales = 'free')+ scale_colour_manual('',values = c("Index k-mer"="black","Total variants"="#f7238a", "Major variant"="#37AFAF","Minor variants"="#42aaff","Unique variants"="#af10f1","Nonatypes"="#c2c7cb" ))+ scale_fill_manual('',values = c("Index k-mer"="black","Total variants"="#f7238a", "Major variant"="#37AFAF","Minor variants"="#42aaff","Unique variants"="#af10f1","Nonatypes"="#c2c7cb" )) } #plot4_5 ggarrange(plot4,plot5,ncol=1,heights = c(1,0.5)) }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/plot_dynamics_protein.R
#' Dynamics of Diversity Motifs (Proteome) Plot #' #' This function compactly display the dynamics of diversity motifs (index and its variants: major, minor and unique) #' in the form of dot plot as well as violin plot for all the provided proteins at proteome level. #' #' @param df DiMA JSON converted csv file data #' @param host number of host (1/2) #' @param line_dot_size size of dot in plot #' @param base_size word size in plot #' @param alpha any number from 0 (transparent) to 1 (opaque) #' @param bw smoothing bandwidth of violin plot (default: nrd0) #' @param adjust adjust the width of violin plot (default: 1) #' @return A plot #' @examples plot_dynamics_proteome(proteins_1host) #' @importFrom gridExtra grid.arrange #' @export plot_dynamics_proteome <- function(df, host=1, line_dot_size=2, base_size=15, alpha=1/3, bw = "nrd0", adjust = 1){ #single host if (host == 1){ plot3(data=df, base_size= base_size, alpha=alpha, line_dot_size=line_dot_size, bw = bw, adjust = adjust) }else{ #multihost #split the data into multiple subsets (if multiple hosts detected) plot3_list<-split(df,df$host) plot3_multihost<-lapply(plot3_list, plot3, line_dot_size, base_size, alpha, bw, adjust) #create spacing between multihost plots theme = theme(plot.margin = unit(c(0.5,1.0,0.1,0.5), "cm")) do.call("grid.arrange", c(grobs=lapply(plot3_multihost,"+",theme), ncol = length(unique(df$host)))) } } #' @importFrom ggplot2 element_blank facet_wrap scale_colour_manual #' @importFrom ggplot2 guides guide_legend scale_color_manual ggtitle element_text geom_violin geom_boxplot ylim scale_color_grey margin scale_fill_manual #' @importFrom ggpubr annotate_figure ggarrange text_grob plot3<-function(data, line_dot_size=2, base_size=15, host = 1, alpha=1/3, bw = "nrd0", adjust = 1){ Total_Variants <- Incidence <- Group <- x <- NULL plot3_data<-data.frame() group_names<-c("Index", "Major", "Minor", "Unique", "Total variants","Distinct variants") #transpose the data format for (i in 7:12){ tmp<-data.frame(proteinName=data[1],position=data[2],incidence=data[i],total_variants=data[11],Group=group_names[i-6],Multiindex=data[13]) names(tmp)[3]<-"Incidence" names(tmp)[4]<-"Total_Variants" plot3_data<-rbind(plot3_data,tmp) } plot3b_data<-plot3_data minor<-rbind(plot3_data[plot3_data$Group == "Index",],plot3_data[plot3_data$Group == "Total variants",]) uniq<-rbind(plot3_data[plot3_data$Group == "Index",],plot3_data[plot3_data$Group == "Total variants",]) minor$motif<- "Minor" uniq$motif<-"Unique" plot3_data<-plot3_data%>%mutate(motif = case_when( plot3_data$Group == "Index" ~ "Major", plot3_data$Group == "Total variants" ~ "Major", plot3_data$Group == "Major" ~ "Major", plot3_data$Group == "Minor" ~ "Minor", plot3_data$Group == "Unique" ~ "Unique", plot3_data$Group == "Distinct variants" ~ "Distinct variants" )) plot3_data<- rbind(plot3_data,minor,uniq) plot3_data$motif<-factor(plot3_data$motif,levels = c("Major","Minor","Unique","Distinct variants")) if (host == 1){ #one host ROW=1 }else{ ROW=2 } #plotting 3a plot3a<-ggplot()+geom_point(plot3_data,mapping=aes(x=Total_Variants,y=Incidence,color=Group),alpha=alpha,size= line_dot_size)+ geom_point(plot3_data,mapping = aes(x =Total_Variants,y=Incidence),col=ifelse(plot3_data$multiIndex== TRUE & plot3_data$Group== "Index", 'red', ifelse(plot3_data$multiIndex== FALSE, 'white', 'white')), alpha=ifelse(plot3_data$multiIndex ==TRUE & plot3_data$Group== "Index", 1, ifelse(plot3_data$multiIndex== TRUE, 0,0)),pch=1,size=3,stroke=1.05)+ #multiIndex scale_x_continuous(limits = c(0, 100), breaks = seq(0, 100, 20))+ scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, 20))+ theme_classic(base_size = base_size)+ theme( panel.border = element_rect(colour = "black", fill=NA, size=1), strip.text.x = element_blank(), legend.position="bottom")+ labs(y= "Incidence (%)", x="\nTotal variants (%)")+ facet_wrap(~ motif,ncol = 1)+ guides(colour = guide_legend(override.aes = list(alpha = 1,size=2),keywidth = 1,keyheight = 1,nrow = ROW))+ scale_colour_manual('',breaks=c("Index","Total variants","Major","Minor","Unique","Distinct variants"), values = c("Index"="black", "Total variants"="#f7238a","MultiIndex"="red", "Major"="#37AFAF" , "Minor"="#42aaff","Unique"="#af10f1", "Distinct variants"="#c2c7cb")) #host label if("host" %in% colnames(data)){ plot3a<-plot3a+ggtitle(unique(data$host))+theme(plot.title = element_text(hjust = 0.5)) } #PLOT 3b index<-plot3b_data[plot3b_data$Group %in% "Index",] nonatypes<-plot3b_data[plot3b_data$Group %in% "Distinct variants",] variants<-plot3b_data[plot3b_data$Group %in% c("Major","Minor","Unique"),] variants$x<-"x" variants_max_yaxis<-ceiling((max(as.numeric(variants$Incidence))/10))*10 #plot 3b plot3b_index<-ggplot(index, aes(x=Group,y=Incidence))+ geom_violin(color="black",fill="black",alpha=0.9, adjust=adjust, bw=bw)+ geom_boxplot(width=0.08,alpha=0.20,fill="white",outlier.shape=NA,color="white")+ ylim(c(0,100))+ labs(y=NULL,x="Index")+ theme_classic(base_size = base_size)+ theme( panel.border = element_rect(colour = "black", fill=NA, size=1), axis.text.x = element_blank(), axis.ticks.x = element_blank())+ scale_color_grey() plot3b_tv<-ggplot(index, aes(x=Group,y=Total_Variants))+ geom_violin(color="#f7238a",fill="#f7238a", alpha=0.9, adjust=adjust, bw=bw)+ geom_boxplot(width=0.08,alpha=0.20,color="black",fill="white",outlier.shape=NA)+ ylim(c(0,100))+ labs(y=NULL,x="Total Variants")+ theme_classic(base_size = base_size)+ theme( plot.margin = margin( t=5, b=5, r = -0.25), panel.border = element_rect(colour = "black", fill=NA, size=1), axis.text=element_text(colour="white"), axis.text.x = element_blank(), axis.ticks = element_blank()) plot3b_nonatype<-ggplot(nonatypes, aes(x=Group,y=Incidence))+ geom_violin(color="#c2c7cb",fill="#c2c7cb", alpha=0.9, adjust=adjust, bw=bw)+ geom_boxplot(width=0.08,alpha=0.20,fill="white",outlier.shape=NA)+ ylim(c(0,100))+ labs(y=NULL,x="Distinct variants")+ theme_classic(base_size = base_size)+ theme( panel.border = element_rect(colour = "black", fill=NA, size=1), axis.text=element_text(colour="white"), axis.text.x = element_blank(), axis.ticks = element_blank()) plot3b_variants<-ggplot(variants)+ geom_violin(mapping=aes(x=x,y=Incidence,color=Group,fill=Group),alpha=0.9, adjust=adjust, bw=bw)+ geom_boxplot(mapping = aes(x=x,y=Incidence),width=0.08,alpha=0.20,fill="white",outlier.shape=NA)+ scale_y_continuous(position = "right",limits = c(0,variants_max_yaxis))+ theme_classic(base_size = base_size-2)+ labs(y=NULL,x=NULL)+ facet_wrap(Group ~ .,ncol=1,strip.position ="right")+ theme(strip.placement = "outside", panel.border = element_rect(colour = "black", fill=NA, size=1), axis.text.x=element_blank (), axis.ticks.x=element_blank (), panel.spacing = unit(0, "lines"), strip.background=element_blank (), axis.text.y = element_text(size=base_size/2-1), plot.margin = margin(t=5,l = -0.1) )+ scale_colour_manual('',values = c( "Major"="#37AFAF","Minor"="#42aaff","Unique"="#af10f1" ))+ scale_fill_manual('',values = c( "Major"="#37AFAF","Minor"="#42aaff","Unique"="#af10f1" ))+ guides(fill="none",color='none') #annotate the violin plot plot3b_variants<-annotate_figure(plot3b_variants,bottom = text_grob("a\n",size=ceiling(base_size/2) ,color = "white")) plot3b<-ggarrange(plot3b_index, plot3b_tv,plot3b_variants, plot3b_nonatype, ncol=4,widths = c(1,0.9,0.95,1)) plot3b<-annotate_figure(plot3b,left = text_grob("Incidence (%)",size=base_size,rot=90,hjust=0.3)) #combine both the top scatter plot and bottom violin plot ggarrange(plot3a,plot3b,ncol=1,heights = c(1,0.3)) }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/plot_dynamics_proteome.R
#' Entropy plot #' #' This function plot entropy (black) and total variant (red) incidence of each #' k-mer position across the studied proteins and highlight region(s) with zero entropy in yellow. #' k-mer position with low support is marked with a red triangle underneath the x-axis line. #' #' @param df DiMA JSON converted csv file data #' @param host number of host (1/2) #' @param protein_order order of proteins displayed in plot #' @param kmer_size size of the k-mer window #' @param ymax maximum y-axis #' @param line_dot_size size of the line and dot in plot #' @param base_size word size in plot #' @param all plot both the entropy and total variants (pass FALSE in to plot only the entropy) #' @param highlight_zero_entropy highlight region with zero entropy (default: TRUE) #' @return A plot #' @examples plot_entropy(proteins_1host) #' @examples plot_entropy(protein_2hosts, host = 2) #' @importFrom ggplot2 geom_rect geom_area geom_hline geom_line facet_grid #' @importFrom ggplot2 sec_axis element_line scale_colour_manual scale_linetype_manual #' @export plot_entropy <- function(df, host=1, protein_order="", kmer_size=9, ymax = 10, line_dot_size=2, base_size=8, all= TRUE, highlight_zero_entropy=TRUE){ entropy <- end <- lowSupportPos <- totalVariants.incidence <- NULL #determine number of host #scale the amino acid position for each protein if (host ==1){ #single host if (protein_order ==""){ a<-table(df$proteinName) proteinName<-as.vector(names(a)) position<-as.vector(a) df$size_f = factor(df$proteinName,levels = proteinName) scales_x<-mapply(function(x,y){ x = scale_x_continuous(limits = c(0,y),breaks = seq(0,y,50)) }, proteinName,position) }else{ #order the proteins based on user input level<-strsplit(protein_order, ',')[[1]] position<-c() for (i in level){ position<-append(position,table(df$proteinName)[names(table(df$proteinName)) == i]) } df$size_f = factor(df$proteinName,levels = level) scales_x<-mapply(function(x,y){ x = scale_x_continuous(limits = c(0,y),breaks = seq(0,y,50)) }, level,position) } }else{ # multihost #categorise data based on host df$host<- factor(df$host) #count the aa length for each proteins (each host is expected to have same number of proteins with same length) df_sub<-df[df$host==unique(df$host[1]),] if (protein_order ==""){ a<-table(df_sub$proteinName) proteinName<-as.vector(names(a)) position<-as.vector(a) df$size_f = factor(df$proteinName,levels = proteinName) scales_x<-mapply(function(x,y){ x = scale_x_continuous(limits = c(0,y),breaks = seq(0,y,50)) }, proteinName,position) }else{ #order the proteins based on user input level<-strsplit(protein_order, ',')[[1]] position<-c() for (i in level){ position<-append(position,table(df_sub$proteinName)[names(table(df_sub$proteinName)) == i]) } df$size_f = factor(df$proteinName,levels = level) scales_x<-mapply(function(x,y){ x = scale_x_continuous(limits = c(0,y),breaks = seq(0,y,50)) }, level,position) } } #---------------set zero entropy region-----------------# #check if the kmer positions are zero entropy #Reference for getting all the positions of kmer based on kmer size and the starting position of kmer: #https://stackoverflow.com/questions/31120552/generate-a-sequence-of-numbers-with-repeated-intervals #https://stackoverflow.com/questions/41637518/adding-a-shaded-rectangle-to-an-existing-plot-using-geom-rect if(highlight_zero_entropy){ #identify the kmer position with zero entropy #position: startPosition with zero entropy #end: startPosition + kmersize - 1 df_zeroEntropy<- df %>% dplyr::group_by(proteinName)%>% dplyr::summarize( end = position[which(entropy == min(entropy))+kmer_size-1], #end: startPosition + kmersize - 1 position = position[which(entropy == min(entropy))] #extract those starting positions with zero entropy )%>% as.data.frame() #concatenate df with df_zeroEntropy df <-merge(df,df_zeroEntropy,id="position",all=T) #replace NAN in column "zero entropy" with FALSE df$end[is.na(df$end)]<- -1 } #---------------set maximum y limit-----------------# #if the max y value in data < 10 => ymax = 10 #if max y value in data > 10 => ymax = ceiling(max y value) if (max(df$entropy) <= 10){ ymax <-10.0 }else if (max(df$entropy) > 10){ ymax <- ceiling(max(df$entropy)) } breaks_fun <- function(x) { seq(0,max(x),50) } limits_fun <- function(x) { c(0,max(x)) } #----------------plotting--------------------# df$lowSupportPos <- -0.3 df$lowSupportPos[df$lowSupport ==TRUE]<- -0.5 plot1<-ggplot(df) + geom_area(mapping = aes(x = position, y = entropy,color= "k-mer Entropy", linetype="k-mer Entropy"), show.legend=F)+ geom_hline(mapping = aes(yintercept=9.2, color = "Reference: Maximum Entropy (9.2) for HIV-1 Clade B (Env Protein)", linetype = "Reference: Maximum Entropy (9.2) for HIV-1 Clade B (Env Protein)"), linewidth= (line_dot_size/10))+ labs(y = "k-mer entropy (bits)\n",x= "\nk-mer position (aa)",color = "#f7238a")+ scale_x_continuous(limits = limits_fun,breaks = breaks_fun)+ theme_classic(base_size = base_size) + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line.y.right = element_line(color = "#f7238a"), axis.ticks.y.right = element_line(color = "#f7238a"), axis.title.y.right = element_text(color = "#f7238a"), legend.position="bottom" )+ scale_colour_manual("", values = c("Reference: Maximum Entropy (9.2) for HIV-1 Clade B (Env Protein)"="black", "k-mer Entropy" = "black"), guide = guide_legend(override.aes=aes(fill=NA)))+ scale_linetype_manual("",values=c("Reference: Maximum Entropy (9.2) for HIV-1 Clade B (Env Protein)"=5, "k-mer Entropy" = 1)) # detect if low support present if (TRUE %in% df$lowSupport){ plot1 <- plot1 + geom_point(mapping = aes(x = position,y=lowSupportPos),col=ifelse(df$lowSupportPos==-0.5, 'black', ifelse(df$lowSupportPos==-0.3, 'white', 'white')), alpha=ifelse(df$lowSupportPos==-0.5, 1, ifelse(df$lowSupportPos==-0.3, 0,0)),pch=17) } # highlight region with zero entropy if(highlight_zero_entropy){ plot1<- plot1+ geom_rect(inherit.aes = FALSE, aes(xmin=position, xmax=end, ymin=-Inf, ymax=+Inf), fill='#FFECAF', alpha=ifelse(df$end == -1, 0, 0.5)) } # plot both entropy and total variants if(all){ plot1<- plot1 + geom_line(mapping = aes(x = position, y = totalVariants.incidence * ymax / 100, color = "Total Variants",linetype="Total Variants"), linewidth= (line_dot_size/10) )+ geom_hline(mapping = aes( yintercept=98* ymax / 100, color = "Reference: Maximum Total Variants (98%) for HIV-1 Clade B (Env Protein)",linetype ="Reference: Maximum Total Variants (98%) for HIV-1 Clade B (Env Protein)"), linewidth= (line_dot_size/10))+ #how to second y-axis: https://whatalnk.github.io/r-tips/ggplot2-rbind.nb.html scale_y_continuous(sec.axis = sec_axis(~ . * 100 / ymax , name = "Total variants (%)",breaks = c(0,25,50,75,100),labels=c("0","25","50","75","100")), breaks = seq(0.0, ymax, length.out = 5),labels= sprintf(seq(0.0, ymax, length.out = 5), fmt = "%.1f")) + scale_colour_manual("", values = c("Reference: Maximum Total Variants (98%) for HIV-1 Clade B (Env Protein)"="#f7238a", "Reference: Maximum Entropy (9.2) for HIV-1 Clade B (Env Protein)"="black", "k-mer Entropy" = "black", "Total Variants"="#f7238a"), guide = guide_legend(override.aes=aes(fill=NA)))+ scale_linetype_manual("",values=c("Reference: Maximum Total Variants (98%) for HIV-1 Clade B (Env Protein)"=5, "Reference: Maximum Entropy (9.2) for HIV-1 Clade B (Env Protein)"=5, "k-mer Entropy" = 1, "Total Variants"=1)) } #number of host if (host == 1){ #one host plot1 +facet_grid(cols=vars(df$size_f),scales = 'free',space = "free",switch = "x") }else{ # multi host plot1 +facet_grid(rows = vars(df$host),cols=vars(df$size_f),scales = 'free',space = "free",switch = "both") } }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/plot_entropy.R
#' Time Distribution of Sequences Plot #' #' This function plots the time distribution of provided sequences in the form of bar plot with 'Month' as x-axis and #' 'Number of Sequences' as y-axis. Aside from the plot, this function also returns a dataframe with 2 columns: 'Date' and 'Number of sequences'. #' The input dataframe of this function is obtainable from metadata_extraction(), with NCBI Protein / GISAID EpiCoV FASTA file as input. #' #' @param metadata a dataframe with 3 columns, 'ID', 'country', and 'date' #' @param base_size word size in plot #' @param date_format date format of the input dataframe #' @param date_break date break for the scale_x_date #' @param scale plot counts or log scale the data #' @param only_plot logical, return only plot or dataframe info as well, default FALSE #' #' @return A single plot or a list with 2 elements (a plot followed by a dataframe, default) #' @examples time_plot <- plot_time(metadata)$plot #' @examples time_df <- plot_time(metadata)$df #' @importFrom ggplot2 scale_x_date geom_bar scale_y_log10 #' @importFrom scales date_format trans_breaks trans_format math_format #' @importFrom stringr str_to_title #' @importFrom magrittr %>% #' @importFrom dplyr filter #' @importFrom purrr .x #' @export plot_time <- function(metadata, date_format = "%Y-%m-%d", base_size=8, date_break = "2 month", scale = "count", only_plot = F){ Month <- .x <- NULL colnames(metadata) <- stringr::str_to_title(colnames(metadata)) dates_3rows<-paste(metadata$Date[1:3], collapse = ", ") metadata <- metadata %>% filter(!is.na(as.Date(metadata$Date, format=date_format, na.rm = TRUE))) if (nrow(metadata) < 1){ error_msg <- paste("No records remain after filtering out those without date format of", date_format, ". Have a peek on some 'Date' values:", dates_3rows) return(error_msg) } metadata$Month <- as.Date(cut(as.Date(metadata$Date, format = date_format), breaks = "month")) p <- ggplot(data = metadata, aes(x = Month)) + geom_bar() + ylab('Number of Sequences') + scale_x_date(date_breaks = date_break, labels = scales::date_format("%Y-%b")) + theme_classic(base_size = base_size) + theme(axis.text.x = element_text(angle = 90, vjust = .5)) if (scale == 'log') { p <- p + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", scales::math_format(10^.x))) } temporal <- metadata[,c('Country', 'Date')] temporal$Count <- 1 temporal$Date <- as.Date(temporal$Date, format = date_format) temporal <- aggregate(temporal$Count, by=list(temporal$Date), sum) colnames(temporal) <- c('Date', 'Number of Sequences') return(list(plot=p,df=temporal)) }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/plot_time.R
#' Geographical Distribution of Sequences Plot #' #' This function plots a worldmap and color the affected geographical region(s) #' from light (lower) to dark (higher), depends on the cumulative number of sequences. #' Aside from the plot, this function also returns a dataframe with 2 columns: 'Country' and 'Number of Sequences'. #' The input dataframe of this function is obtainable from metadata_extraction(), with NCBI #' Protein / GISAID EpiCoV FASTA file as input. #' @param meta a dataframe with 3 columns, 'ID', 'country', and 'date' #' @param base_size word size in plot #' #' @return A list with 2 elements (a plot followed by a dataframe) #' @examples geographical_plot <- plot_worldmap(metadata)$plot #' @examples geographical_df <- plot_worldmap(metadata)$df #' @importFrom ggplot2 geom_polygon scale_fill_gradient map_data #' @importFrom dplyr left_join #' @importFrom stringr str_to_title #' @export plot_worldmap <- function(meta, base_size=8){ long <- lat <- group <- count <- NULL colnames(meta) <- stringr::str_to_title(colnames(meta)) meta <- refineCountry(meta) countrylist <- data.frame(table(meta$Country)) colnames(countrylist) <- c('region','count') world_map <- ggplot2::map_data("world") p <- ggplot(world_map, aes(x = long, y = lat, group = group)) + geom_polygon(fill="lightgray", colour = "#888888") pathogens.map <- dplyr::left_join(countrylist, world_map, by = "region") p <- p + geom_polygon(data = pathogens.map, aes(fill = count), color = "#888888") + scale_fill_gradient(low = "#FFFFFF", high = "#E63F00", name = 'Number of Sequences') + theme(plot.background = element_rect(fill = "transparent", colour = NA), panel.border = element_blank(), panel.grid = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), axis.title = element_blank(), legend.position = "right") + theme_classic(base_size=base_size) colnames(countrylist) <- c('Country','Number of Sequences') return(list(plot=p, df=countrylist)) } refineCountry <- function(metatable){ metatable$Country[metatable$Country == "DRC"] = "Democratic Republic of the Congo" metatable$Country[metatable$Country == "NewCaledonia"] = "New Caledonia" metatable$Country[metatable$Country == "Northern Ireland"] = "UK" metatable$Country[metatable$Country %in% c("England","Scotland","Wales")] = "UK" metatable$Country[metatable$Country %in% c("Shangahi", "Xinjiang","Sichuan", "Guangdong","Shannxi", "Chongqing", "Inner_Mongolia","Shenzhen", "Wuhan", "Fujian", "Inner Mongolia", "Tianjing", "Hebei","Jiangsu", "Shandong", "Zhejiang", "Liaoning","Shanxi", "Henan", "Chongqin", "Yunnan", "Beijing","Heilongjiang", "Hunan", "Guangxi","Ningxia","Jilin","Tibet","Hainan", "Macao", "Jiangxi","Qinghai", "Hubei", "Gansu", "Anhui" ,"Guizhou" )] = "China" return(metatable) }
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/plot_worldmap.R
#' DiMA (v4.1.1) JSON converted-CSV Output Sample 1 #' #' A dummy dataset with two proteins (A and B) from one host, human #' #' #' @format A data frame with 806 rows and 17 variables: #' \describe{ #' \item{proteinName}{name of the protein} #' \item{position}{starting position of the aligned, overlapping k-mer window} #' \item{count}{number of k-mer sequences at the given position} #' \item{lowSupport}{k-mer position with sequences lesser than the minimum support threshold (TRUE) are considered of low support, in terms of sample size} #' \item{entropy}{level of variability at the k-mer position, with zero representing completely conserved} #' \item{indexSequence}{the predominant sequence (index motif) at the given k-mer position} #' \item{index.incidence}{the fraction (in percentage) of the index sequences at the k-mer position} #' \item{major.incidence}{the fraction (in percentage) of the major sequence (the predominant variant to the index) at the k-mer position} #' \item{minor.incidence}{the fraction (in percentage) of minor sequences (of frequency lesser than the major variant, but not singletons) at the k-mer position} #' \item{unique.incidence}{the fraction (in percentage) of unique sequences (singletons, observed only once) at the k-mer position} #' \item{totalVariants.incidence}{the fraction (in percentage) of sequences at the k-mer position that are variants to the index (includes: major, minor and unique variants)} #' \item{distinctVariant.incidence}{incidence of the distinct k-mer peptides at the k-mer position} #' \item{multiIndex}{presence of more than one index sequence of equal incidence} #' \item{host}{species name of the organism host to the virus} #' \item{highestEntropy.position}{k-mer position that has the highest entropy value} #' \item{highestEntropy}{highest entropy values observed in the studied protein} #' \item{averageEntropy}{average entropy values across all the k-mer positions} #' } "proteins_1host" #' DiMA (v4.1.1) JSON converted-CSV Output Sample 2 #' #' A dummy dataset with 1 protein (Core) from two hosts, human and bat #' #' #' @format A data frame with 200 rows and 17 variables: #' \describe{ #' \item{proteinName}{name of the protein} #' \item{position}{starting position of the aligned, overlapping k-mer window} #' \item{count}{number of k-mer sequences at the given position} #' \item{lowSupport}{k-mer position with sequences lesser than the minimum support threshold (TRUE) are considered of low support, in terms of sample size} #' \item{entropy}{level of variability at the k-mer position, with zero representing completely conserved} #' \item{indexSequence}{the predominant sequence (index motif) at the given k-mer position} #' \item{index.incidence}{the fraction (in percentage) of the index sequences at the k-mer position} #' \item{major.incidence}{the fraction (in percentage) of the major sequence (the predominant variant to the index) at the k-mer position} #' \item{minor.incidence}{the fraction (in percentage) of minor sequences (of frequency lesser than the major variant, but not singletons) at the k-mer position} #' \item{unique.incidence}{the fraction (in percentage) of unique sequences (singletons, observed only once) at the k-mer position} #' \item{totalVariants.incidence}{the fraction (in percentage) of sequences at the k-mer position that are variants to the index (includes: major, minor and unique variants)} #' \item{distinctVariant.incidence}{incidence of the distinct k-mer peptides at the k-mer position} #' \item{multiIndex}{presence of more than one index sequence of equal incidence} #' \item{host}{species name of the organism host to the virus} #' \item{highestEntropy.position}{k-mer position that has the highest entropy value} #' \item{highestEntropy}{highest entropy values observed in the studied protein} #' \item{averageEntropy}{average entropy values across all the k-mer positions} #' } "protein_2hosts" #' DiMA (v4.1.1) JSON Output File #' #' A sample DiMA JSON Output File which acts as the input for JSON2CSV() #' #' #' @format A Diversity Motif Analyzer (DiMA) tool JSON file "JSON_sample" #' Metadata Input Sample #' #' A dummy dataset that acts as an input for plot_worldmap() and plot_time() #' #' #' @format A data frame with 1000 rows and 3 variables: #' \describe{ #' \item{ID}{unique identifier of the sequence} #' \item{country}{country of the sequence collection} #' \item{date}{collection date of the sequence} #' } "metadata"
/scratch/gouwar.j/cran-all/cranData/vDiveR/R/sample_data.R
#' Change Group ID #' #' @description Change the group ID to be consequetive numbers, starting at 1, which is #' required for model fitting. #' #' @param group Numeric Vector. The grouping variable (e.g., subjects). #' #' @return Updated group ID. #' #' @examples #' # congruent trials #' dat <- subset(flanker, id %in% c(39, 23, 2)) #' change_group(dat$id) #' @export change_group <- function(group){ x <- rle(group)$lengths new_id <- rep(x = seq_along(x), times = x) return(new_id) }
/scratch/gouwar.j/cran-all/cranData/vICC/R/change_group.R
#' @title Extract the Group-Specific Coefficients #' #' @description Extract the group-specific coefficients #' (fixed effect + random effect). #' #' @aliases coef #' #' @param object An object of class \code{vicc} #' #' @param cred Numeric. Credible interval width (defaults to \code{0.90}). #' #' @param ... Currently ignored. #' #' @return An array with the summarized parameters #' #' @export #' #' @examples #' \donttest{ #' Y <- flanker #' # congruent trials #' congruent <- subset(Y, cond == 0) #' #' # subset 25 from each group #' dat <- congruent[unlist(tapply(1:nrow(congruent), #' congruent$id, #' head, 25)), ] #' #' # fit model #' fit <- vicc(y = dat$rt, #' group = dat$id, #' iter = 250, #' burnin = 10, #' type = "customary") #' #' coef(fit) #' #' } coef.vicc <- function(object, cred = 0.90, ...){ # credible interval lb <- (1 - cred) / 2 ub <- 1 - lb # number of groups J <- object$model$data()$J if (object$type == "customary") { obs_per_group <- tapply(object$model$data()$ID, object$model$data()$ID, length) samps <- posterior_samples(object) array_collect <- array(0, dim = c(J, 4, 3)) dimnames(array_collect)[[1]] <- 1:J dimnames(array_collect)[[3]] <- c("mean", "icc1", "icc2") ranefs <- samps[paste0("beta[", 1:J, "]")] post_mean <- apply(ranefs, 2, mean) post_sd <- apply(ranefs, 2, sd) post_cred <- apply(ranefs, 2, quantile, probs = c(lb, ub)) array_collect[, , 1] <- cbind(post_mean, post_sd, t(post_cred)) icc <- (samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + samps$sigma ^ 2)) post_mean_icc <- mean(icc) post_sd_icc <- sd(icc) post_cred_icc <- quantile(icc, probs = c(lb, ub)) array_collect[, , 2] <- matrix(rep(cbind( post_mean_icc, post_sd_icc, t(post_cred_icc) ), J), nrow = J, ncol = 4, byrow = TRUE) icc <- (samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + (samps$sigma ^2) / mean(obs_per_group))) post_mean_icc <- mean(icc) post_sd_icc <- sd(icc) post_cred_icc <- quantile(icc, probs = c(lb, ub)) array_collect[, , 3] <- matrix(rep(cbind( post_mean_icc, post_sd_icc, t(post_cred_icc) ), J), nrow = J, ncol = 4, byrow = TRUE) # all other models } else { samps <- posterior_samples(object) obs_per_group <- tapply(object$model$data()$ID, object$model$data()$ID, length) array_collect <- array(0, dim = c(J, 4, 4)) dimnames(array_collect)[[1]] <- 1:J dimnames(array_collect)[[3]] <- c("mean", "sd", "icc1", "icc2") # location ranefs_l <- samps[paste0("beta_l[", 1:J, "]")] post_mean_l <- apply(ranefs_l, 2, mean) post_sd_l <- apply(ranefs_l, 2, sd) post_cred_l <- apply(ranefs_l, 2, quantile, probs = c(lb, ub)) array_collect[, , 1] <- cbind(post_mean_l, post_sd_l, t(post_cred_l)) # scale ranefs_s <- exp(samps[paste0("beta_s[", 1:J, "]")]) post_mean_s <- apply(ranefs_s, 2, mean) post_sd_s <- apply(ranefs_s, 2, sd) post_cred_s <- apply(ranefs_s, 2, quantile, probs = c(lb, ub)) array_collect[, , 2] <- cbind(post_mean_s, post_sd_s, t(post_cred_s)) # ICC ranefs_icc1 <- apply( ranefs_s, MARGIN = 2, FUN = function(x) { samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + x ^ 2) } ) post_mean_icc1 <- apply(ranefs_icc1, 2, mean) post_sd_icc1 <- apply(ranefs_icc1, 2, sd) post_cred_icc1 <- apply(ranefs_icc1, 2, quantile, probs = c(lb, ub)) array_collect[, , 3] <- cbind(post_mean_icc1, post_sd_icc1, t(post_cred_icc1)) ranefs_icc2 <- sapply( 1:J, FUN = function(x) { samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + (ranefs_s[, x] ^ 2 / obs_per_group[x])) } ) post_mean_icc2 <- apply(ranefs_icc2, 2, mean) post_sd_icc2 <- apply(ranefs_icc2, 2, sd) post_cred_icc2 <- apply(ranefs_icc2, 2, quantile, probs = c(lb, ub)) array_collect[, , 4] <- cbind(post_mean_icc2, post_sd_icc2, t(post_cred_icc2)) } array_collect <- round(array_collect, 10) dimnames(array_collect)[[2]] <- c("Post.mean", "Post.sd", "Cred.lb", "Cred.ub") returned_object <- list(group = array_collect) class(returned_object) <- "group_parameters" return(returned_object) }
/scratch/gouwar.j/cran-all/cranData/vICC/R/coef_vicc.R
#' @title Data: Flanker Task data from \insertCite{hedge2018reliability;textual}{vICC}. #' #' @description A dataset containing 33660 rows and 7 columns. #' #' \itemize{ #' \item Block #' \item Trial number #' \item Arrow direction (1=left, 2=right) #' \item Condition (0 = congruent, 1=neutral, 2=incongruent) #' \item Correct (1) or incorrect (0) #' \item Reaction time (seconds) #' } #' #' @note #' Reaction times less than 0.20 and greater than 2 seconds were removed. #' #' @docType data #' #' @keywords datasets #' #' @name flanker #' #' @usage data("flanker") #' #' @references #' #' \insertAllCited{} #' #' @format A dataframe 33660 rows and 7 columns. NULL
/scratch/gouwar.j/cran-all/cranData/vICC/R/datasets.R
#' Extract Fixed Effects #' #' @aliases fixef #' #' @description Summarize the fixed effects. #' #' @param object An object of class \code{vicc}. #' #' @param cred Numeric. Credible interval width (defaults to \code{0.90}) #' #' @param ... Currently ignored. #' #' @return Summarized fixed effects #' #' @method fixef vicc #' @export #' @export fixef #' @importFrom nlme fixef #' #' @examples #' \donttest{ #' # data #' Y <- flanker #' #' # congruent trials #' congruent <- subset(Y, cond == 0) #' #' # subset 25 from each group #' dat <- congruent[unlist(tapply(1:nrow(congruent), #' congruent$id, #' head, 25)), ] #' #' fit <- vicc( #' y = dat$rt, #' group = dat$id, #' iter = 250, #' burnin = 10, #' type = "pick_none" #' ) #' #' fixef(fit) #' } fixef.vicc <- function(object, cred = 0.90, ...) { samps <- posterior_samples(object) lb <- (1 - cred) / 2 ub <- 1 - lb if (object$type == "customary") { fixef_summary <- cbind(mean(samps$fe_mu), sd(samps$fe_mu), t(quantile( samps$fe_mu, probs = c(lb, ub) ))) row.names(fixef_summary) <- c("intercept_mean") } else { fixef_summary <- rbind(cbind(mean(samps$fe_mu), sd(samps$fe_mu), t(quantile( samps$fe_mu, probs = c(lb, ub) ))), cbind(mean(exp(samps$fe_sd)), sd(exp(samps$fe_sd)), t(quantile( exp(samps$fe_sd), probs = c(lb, ub) )))) row.names(fixef_summary) <- c("intercept_mean", "intercept_sigma") } colnames(fixef_summary) <- c("Post.mean", "Post.sd", "Cred.lb", "Cred.ub") return(fixef_summary) }
/scratch/gouwar.j/cran-all/cranData/vICC/R/fixef_vicc.R
#' @importFrom methods is #' @importFrom stats quantile sd coef #' @importFrom utils packageVersion ICC_lsm <- "model{ for(j in 1:J){ # latent betas beta_raw_l[j] ~ dnorm(0, 1) # random effect beta_l[j] <- fe_mu + tau_mu * beta_raw_l[j] # cholesky z2[j] ~ dnorm(0, 1) beta_raw_s[j] = rho12 * beta_raw_l[j] + sqrt(1 - rho12^2) * z2[j] beta_s[j] <- fe_sd + tau_sd * beta_raw_s[j] } for(i in 1:N){ # likelihood y[i] ~ dnorm(beta_l[ID[i]], 1/exp(beta_s[ID[i]])^2) } # fixed effects priors fe_mu ~ dnorm(0, 1) fe_sd ~ dnorm(0, 1) # random effects priors tau_mu ~ dt(0, pow(prior_scale,-2), 10)T(0,) tau_sd ~ dt(0, pow(prior_scale,-2), 10)T(0,) # prior for RE correlation fz ~ dnorm(0, 1) rho12 = tanh(fz) }" ICC_customary <- "model{ for(j in 1:J){ # latent betas beta_raw[j] ~ dnorm(0, 1) # random effect beta[j] <- fe_mu + tau_mu * beta_raw[j] } for(i in 1:N){ # likelihood y[i] ~ dnorm(beta[ID[i]], prec) } # fixed effects priors fe_mu ~ dnorm(0, 1) # random effects priors tau_mu ~ dt(0, pow(prior_scale,-2), 10)T(0,) prec ~ dgamma(1.0E-4,1.0E-4) sigma <- 1/sqrt(prec) }" ICC_pick_tau <- "model{ for(j in 1:J){ # latent betas beta_raw_l[j] ~ dnorm(0, 1) # random effect beta_l[j] <- fe_mu + tau_mu * beta_raw_l[j] # cholesky z2[j] ~ dnorm(0, 1) beta_raw_s[j] = rho12 * beta_raw_l[j] + sqrt(1 - rho12^2) * z2[j] beta_s[j] <- fe_sd + tau_new * beta_raw_s[j] } for(i in 1:N){ # likelihood y[i] ~ dnorm(beta_l[ID[i]], 1/exp(beta_s[ID[i]])^2) } # fixed effects priors fe_mu ~ dnorm(0, 1) fe_sd ~ dnorm(0, 1) # random effects priors tau_mu ~ dgamma(1.0E-4,1.0E-4) tau_sd ~ dt(0, pow(prior_scale,-2), 10)T(0,) pick_tau ~ dbern(inc_prob) tau_new <- tau_sd * pick_tau # prior for RE correlation fz ~ dnorm(0, 1) rho12 = tanh(fz) }" ICC_pick_id <- "model{ for(j in 1:J){ pick_id[j] ~ dbern(inc_prob) # latent betas beta_raw_l[j] ~ dnorm(0, 1) # random effect beta_l[j] <- fe_mu + tau_mu * beta_raw_l[j] # cholesky z2[j] ~ dnorm(0, 1) beta_raw_s[j] = rho12 * beta_raw_l[j] + sqrt(1 - rho12^2) * z2[j] beta_new[j] <- beta_raw_s[j] * pick_id[j] beta_s[j] <- fe_sd + (tau_sd * beta_new[j]) } for(i in 1:N){ # likelihood y[i] ~ dnorm(beta_l[ID[i]], 1/exp(beta_s[ID[i]])^2) } # fixed effects priors fe_mu ~ dnorm(0, 1) fe_sd ~ dnorm(0, 1) # random effects priors tau_mu ~ dt(0, pow(prior_scale,-2), 10)T(0,) tau_sd ~ dt(0, pow(prior_scale,-2), 10)T(0,) # prior for RE correlation fz ~ dnorm(0, 1) rho12 = tanh(fz) }" globalVariables(c("group_color", "group", "Post.mean", "Cred.lb", "Cred.ub", "PIP")) viccStartupMessage <- function(){ msg <- c(paste0( " _______ _____ _____ /|| // // ____ //|| // // \\\\ // || || || \\\\ // || || || \\ / || \\\\ \\\\ / ___||__ \\\\___\\\\____ ", "\nVersion ", packageVersion("vICC")), "\nType 'citation(\"vICC\")' for citing this R package.") return(msg) } .onAttach <- function(lib, pkg){ # startup message msg <- viccStartupMessage() if(!interactive()) msg[1] <- paste("Package 'vICC' version", packageVersion("vICC")) packageStartupMessage(msg) invisible() }
/scratch/gouwar.j/cran-all/cranData/vICC/R/helpers.R
#' @title Posterior Inclusion Probabilities #' #' @description Extract the posterior inclusion probabilities (PIP) for either the #' random intercepts for sigma or the random effects standard deviation #' for sigma. #' #' @param object Ab object of class \code{vicc}. #' #' @param ... Currently ignored. #' #' @return A data frame. #' #' @note The PIPs indicate whether the groups differ from the fixed effect, or average, #' within-group variance. If the PIP is large, this indicates there is high probability #' that group differs from the common variance. A marginal Bayes factor can be computed #' as PIP / (1 - PIP), assuming that \code{prior_prob = 0.5}. #' #' @export #' #' @examples #' \donttest{ #' #' # congruent trials #' congruent <- subset(flanker, cond == 0) #' #' # subset 25 from each group #' dat <- congruent[unlist(tapply(1:nrow(congruent), #' congruent$id, #' head, 25)), ] #' #' # fit model #' fit <- vicc(y = dat$rt, #' group = dat$id, #' iter = 250, #' burnin = 10, #' type = "pick_group") #' #' pip(fit) #' } pip <- function(object, ...){ samps <- posterior_samples(object) if (object$type == "pick_group") { J <- object$model$data()$J pips <- colMeans(samps[, grep("pick_id", x = colnames(samps))]) pip_summary <- data.frame(Parameter = paste0("RE_", 1:J), Group = 1:J, PIP = pips) row.names(pip_summary) <- NULL } else if (object$type == "pick_tau") { pips <- mean(samps[, grep("pick_tau", x = colnames(samps))]) pip_summary <- data.frame(Param = "RE_sd_sigma", PIP = pips) row.names(pip_summary) <- NULL } else { stop("type not supported.") } returned_object <- list(pip_summary = pip_summary) class(returned_object) <- "pip" return(returned_object) } #' Print \code{pip} Objects #' #' @param x An object of class \code{pip}. #' @param ... Currently ignored. #' #' @export print.pip <- function(x, ...){ cat("Posterior Inclusion Probabilities:\n\n") print(x$pip_summary, row.names = FALSE, right = FALSE) cat("\n") cat("------") }
/scratch/gouwar.j/cran-all/cranData/vICC/R/pip.R
#' Plot \code{pip} Objects #' #' @description Bar plot for the posterior inclusion probabilities, which corresponds to #' the probability that each group differs from the average within-group #' variance. #' #' @param x An object of class \code{pip}. #' #' @param fill Character string. Which color for the bars #' (defaults to \code{black})? #' #' @param width Numeric. The width for the bars (defaults to \code{0.5}). #' #' @param ... Currently ignored #' #' @return A \code{ggplot} object. #' #' @export #' #' @importFrom ggplot2 geom_bar scale_y_discrete ylab #' #' @examples #' \donttest{ #' #' # congruent trials #' congruent <- subset(flanker, cond == 0) #' #' # subset 25 from each group #' dat <- congruent[unlist(tapply(1:nrow(congruent), #' congruent$id, #' head, 25)), ] #' fit <- vicc( #' y = dat$rt, #' group = dat$id, #' iter = 500, #' burnin = 10, #' type = "pick_group" #' ) #' #' pips <- pip(fit) #' #' plot(pips) #' #' } plot.pip <- function(x, fill = "black", width = 0.5, ...){ dat_plot <- x$pip_summary # check for pips if(nrow(dat_plot) ==1){ stop("type not supported. must be 'tick_group'") } dat_plot <- dat_plot[order(dat_plot$PIP), ] dat_plot$group <- 1:nrow(dat_plot) plt <- ggplot(dat_plot, aes(x = PIP, y = as.factor(group))) + geom_bar(stat = "identity", width = 0.5, fill = fill) + scale_y_discrete(labels = row.names(dat_plot)) + ylab("Group") return(plt) }
/scratch/gouwar.j/cran-all/cranData/vICC/R/plot_pip.R
#' @title Plot \code{vicc} Objects #' #' @description Plot the group-specific coefficients or the random effects. #' #' @param x An object of class \code{vicc}. #' #' @param type Character string. Which parameters should be plotted? The options are #' \code{ranef} and \code{coef} (the default). #' #' @param ... Currently ignored. #' #' @return A \code{ggplot} object. #' #' @export #' #' @importFrom ggplot2 aes geom_hline geom_point geom_errorbar ggtitle ggplot #' #' #' @examples #' \donttest{ #' # congruent trials #' congruent <- subset(flanker, cond == 0) #' #' # subset 25 from each group #' dat <- congruent[unlist(tapply(1:nrow(congruent), #' congruent$id, #' head, 25)), ] #' #' # fit model #' fit <- vicc(y = dat$rt, #' group = dat$id, #' iter = 250, #' burnin = 10, #' type = "customary") #' #' plts <- plot(fit) #'} plot.vicc <- function(x , type = "coef", ...) { # posterior samples samps <- posterior_samples(x) obs_per_group <- tapply(x$model$data()$ID, x$model$data()$ID, length) if (type == "coef") { if (x$type == "customary") { icc1 <- mean((samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + (samps$sigma) ^ 2))) icc2 <- mean((samps$tau_mu ^ 2 / ( samps$tau_mu ^ 2 + (samps$sigma) ^ 2 / mean(obs_per_group) ))) # mean coefs <- coef(x) n_plots <- dim(coefs$group)[3] plots <- list() temp <- coefs$group[, , 1] dat <- as.data.frame(temp[order(temp[, 1]),]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < fixef(x)[1, 1] & dat$Cred.ub > fixef(x)[1, 1], 0 , 1)) plot_mean <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = fixef(x)[1, 1]) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][1]) # icc1 coefs <- coef(x) n_plots <- dim(coefs$group)[3] plots <- list() temp <- coefs$group[, , 2] dat <- as.data.frame(temp[order(temp[, 1]),]) dat$group <- 1:nrow(dat) plot_icc1 <- ggplot(dat, aes(x = as.factor(group), y = Post.mean)) + geom_hline(yintercept = icc1) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][2]) # icc2 coefs <- coef(x) n_plots <- dim(coefs$group)[3] plots <- list() temp <- coefs$group[, , 3] dat <- as.data.frame(temp[order(temp[, 1]),]) dat$group <- 1:nrow(dat) plot_icc2 <- ggplot(dat, aes(x = as.factor(group), y = Post.mean)) + geom_hline(yintercept = icc2) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][3]) returned_object <- list(plot_mean = plot_mean, plot_icc1 = plot_icc1, plot_icc2 = plot_icc2) } else { icc1 <- mean((samps$tau_mu ^ 2 / ( samps$tau_mu ^ 2 + exp(samps$fe_sd) ^ 2 ))) icc2 <- mean((samps$tau_mu ^ 2 / ( samps$tau_mu ^ 2 + exp(samps$fe_sd) ^ 2 / mean(obs_per_group) ))) coefs <- coef(x) # mean temp <- coefs$group[, , 1] dat <- as.data.frame(temp[order(temp[, 1]), ]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < fixef(x)[1, 1] & dat$Cred.ub > fixef(x)[1, 1], 0 , 1)) plot_mean <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = fixef(x)[1, 1]) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][1]) # sd coefs <- coef(x) temp <- coefs$group[, , 2] dat <- as.data.frame(temp[order(temp[, 1]), ]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < fixef(x)[2, 1] & dat$Cred.ub > fixef(x)[2, 1], 0 , 1)) plot_sd <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = fixef(x)[2, 1]) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][2]) # icc1 coefs <- coef(x) temp <- coefs$group[, , 3] dat <- as.data.frame(temp[order(temp[, 1]), ]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < icc1 & dat$Cred.ub > icc1, 0 , 1)) plot_icc1 <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = icc1) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][3]) # icc2 coefs <- coef(x) temp <- coefs$group[, , 4] dat <- as.data.frame(temp[order(temp[, 1]), ]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < icc2 & dat$Cred.ub > icc2, 0 , 1)) plot_icc2 <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = icc2) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][4]) returned_object <- list( plot_mean = plot_mean, plot_sd = plot_sd, plot_icc1 = plot_icc1, plot_icc2 = plot_icc2 ) } } else if (type == "ranef") { if (x$type == "customary") { # mean coefs <- ranef(x) temp <- coefs$group[, , 1] dat <- as.data.frame(temp[order(temp[, 1]),]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < 0 & dat$Cred.ub > 0, 0 , 1)) plot_mean <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = 0) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][1]) returned_object <- list(plot_mean = plot_mean) } else { coefs <- ranef(x) # mean temp <- coefs$group[, , 1] dat <- as.data.frame(temp[order(temp[, 1]), ]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < 0 & dat$Cred.ub > 0, 0 , 1)) plot_mean <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = 0) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][1]) # sd temp <- coefs$group[, , 2] dat <- as.data.frame(temp[order(temp[, 1]), ]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < 0 & dat$Cred.ub > 0, 0 , 1)) plot_sd <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = 0) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][2]) # icc1 temp <- coefs$group[, , 3] dat <- as.data.frame(temp[order(temp[, 1]), ]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < 0 & dat$Cred.ub > 0, 0 , 1)) plot_icc1 <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = 0) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][3]) # icc2 temp <- coefs$group[, , 4] dat <- as.data.frame(temp[order(temp[, 1]), ]) dat$group <- 1:nrow(dat) dat$group_color <- as.factor(ifelse(dat$Cred.lb < 0 & dat$Cred.ub > 0, 0 , 1)) plot_icc2 <- ggplot(dat, aes( x = as.factor(group), y = Post.mean, color = group_color )) + geom_hline(yintercept = 0) + geom_point() + geom_errorbar(aes(ymin = Cred.lb, ymax = Cred.ub)) + ggtitle(dimnames(coefs$group)[[3]][4]) returned_object <- list( plot_mean = plot_mean, plot_sd = plot_sd, plot_icc1 = plot_icc1, plot_icc2 = plot_icc2 ) } } else { stop("type not supported. must be 'coef' or 'ranef'") } return(returned_object) }
/scratch/gouwar.j/cran-all/cranData/vICC/R/plot_vicc.R
#' @title Extract Posterior Samples #' #' @description Extract posterior samples for \code{vicc} objects #' #' @param object An object of class \code{vicc} #' #' @return An object of class \code{data.frame} #' #' @export #' #' @importFrom coda as.mcmc.list #' #' @examples #' \donttest{ #' # congruent trials #' congruent <- subset(flanker, cond == 0) #' #' # subset 25 from each group #' dat <- congruent[unlist(tapply(1:nrow(congruent), #' congruent$id, #' head, 25)), ] #' #' # fit model #' fit <- vicc(y = dat$rt, #' group = dat$id, #' iter = 250, #' burnin = 10, #' type = "customary") #' #' samps <- posterior_samples(fit) #'} posterior_samples <- function(object){ if(!is(object, "vicc")){ stop("object must be of class 'vicc'") } samples <- do.call(rbind.data.frame, lapply(1:object$chains, function(x) coda::as.mcmc.list(object$fit)[[x]][-c(1:object$burnin), ])) return(samples) }
/scratch/gouwar.j/cran-all/cranData/vICC/R/posterior_samples.R
#' @title Extract the Random Effects #' #' @aliases ranef #' #' @description Extract the group-specific parameter estimates. #' #' @inheritParams coef.vicc #' #' @return An array with the summarized parameters. #' #' @method ranef vicc #' @export #' @export ranef #' @importFrom nlme ranef #' #' @examples #' \donttest{ #' #' flanker <- vICC::flanker #' #' # congruent trials #' congruent <- subset(flanker, cond == 0) #' #' # subset 25 from each group #' dat <- congruent[unlist(tapply(1:nrow(congruent), #' congruent$id, #' head, 25)), ] #' #' # fit model #' fit <- vicc(y = dat$rt, #' group = dat$id, #' iter = 250, #' burnin = 10, #' type = "customary") #' #' ranef(fit) #' } ranef.vicc <- function(object, cred = 0.90, ...){ lb <- (1 - cred) / 2 ub <- 1 - lb J <- object$model$data()$J if(object$type == "customary"){ samps <- posterior_samples(object) means <- samps$fe_mu array_collect <- array(0, dim = c(J, 4, 1)) dimnames(array_collect)[[1]] <- 1:J dimnames(array_collect)[[3]] <- c("mean") ranefs <- samps[paste0("beta[", 1:J, "]")] ranefs <- ranefs - means post_mean <- apply(ranefs, 2, mean) post_sd <- apply(ranefs, 2, sd) post_cred <- apply(ranefs, 2, quantile, probs = c(lb, ub)) array_collect[,,1] <- round(cbind(post_mean, post_sd, t(post_cred)), 10) } else { samps <- posterior_samples(object) means <- samps$fe_mu sds <- samps$fe_sd obs_per_group <- tapply(object$model$data()$ID, object$model$data()$ID, length) array_collect <- array(0, dim = c(J, 4, 4)) dimnames(array_collect)[[1]] <- 1:J dimnames(array_collect)[[3]] <- c("mean", "sd", "icc1", "icc2") # location ranefs_l <- samps[paste0("beta_l[", 1:J, "]")] ranefs_l <- ranefs_l - means post_mean_l <- apply(ranefs_l, 2, mean) post_sd_l <- apply(ranefs_l, 2, sd) post_cred_l <- apply(ranefs_l, 2, quantile, probs = c(lb, ub)) array_collect[,,1] <- cbind(post_mean_l, post_sd_l, t(post_cred_l)) # scale ranefs_s <- exp(samps[paste0("beta_s[", 1:J, "]")]) - exp(sds) post_mean_s <- apply(ranefs_s, 2, mean) post_sd_s <- apply(ranefs_s, 2, sd) post_cred_s <- apply(ranefs_s, 2, quantile, probs = c(lb, ub)) array_collect[,,2] <- cbind(post_mean_s, post_sd_s, t(post_cred_s)) icc <-(samps$tau_mu^2 / (samps$tau_mu^2 + exp(sds)^2)) ranefs_s <- exp(samps[paste0("beta_s[", 1:J, "]")]) # ICC ranefs_icc1 <- apply(ranefs_s, MARGIN = 2, FUN = function(x) { samps$tau_mu^2 / (samps$tau_mu^2 + x^2) }) ranefs_icc1 <- ranefs_icc1 - icc post_mean_icc1 <- apply(ranefs_icc1, 2, mean) post_sd_icc1 <- apply(ranefs_icc1, 2, sd) post_cred_icc1 <- apply(ranefs_icc1, 2, quantile, probs = c(lb, ub)) array_collect[, , 3] <- cbind(post_mean_icc1, post_sd_icc1, t(post_cred_icc1)) icc2 <-(samps$tau_mu^2 / (samps$tau_mu^2 + exp(sds)^2 / mean(obs_per_group))) ranefs_icc2 <- sapply(1:J, FUN = function(x) { samps$tau_mu^2 / (samps$tau_mu^2 + (ranefs_s[,x]^2 / obs_per_group[x]) ) }) ranefs_icc2 <- ranefs_icc2 - icc2 post_mean_icc2 <- apply(ranefs_icc2, 2, mean) post_sd_icc2 <- apply(ranefs_icc2, 2, sd) post_cred_icc2 <- apply(ranefs_icc2, 2, quantile, probs = c(lb, ub)) array_collect[, , 4] <- cbind(post_mean_icc2, post_sd_icc2, t(post_cred_icc2)) } dimnames(array_collect)[[2]] <- c("Post.mean", "Post.sd", "Cred.lb", "Cred.ub") returned_object <- list(group = array_collect) class(returned_object) <- "group_parameters" return(returned_object) }
/scratch/gouwar.j/cran-all/cranData/vICC/R/ranef_vicc.R
sem <- function(object, cred = 0.95, ...){ if(!is(object, "vicc")){ stop("object must be of class 'vicc'") } samps <- posterior_samples(object) lb <- (1 - cred) / 2 ub <- 1 - lb if(object$type == "customary"){ obs_per_group <- tapply(object$model$data()$ID, object$model$data()$ID, length) sem <- samps$sigma / sqrt(mean(obs_per_group)) sem_summary <- data.frame(Post.mean = mean(sem), Post.sd = sd(sem), t(quantile(sem, probs = c(lb, ub)) )) colnames(sem_summary)[3:4] <- c("Cred.lb", "Cred.ub") class(sem_summary) <- c("sem", "data.frame") returned_object <- sem_summary } else { obs_per_group <- tapply(object$model$data()$ID, object$model$data()$ID, length) sem <- exp(samps$fe_sd) / sqrt(mean(obs_per_group)) sem_summary <- data.frame(Post.mean = mean(sem), Post.sd = sd(sem), t(quantile(sem, probs = c(lb, ub)) )) df <- t(as.matrix(obs_per_group)) mat <- sqrt(t(do.call(rbind, lapply(df, rep, nrow(samps)) ))) array_collect <- array(0, c(length(obs_per_group), 4, 1 )) sem <- exp(samps[, grep("beta_s", colnames(samps))]) /mat post_mean_sem <- apply(sem, 2, mean) post_sd_sem <- apply(sem, 2, sd) post_q_sem <- apply(sem, 2, quantile, probs = c(lb, ub)) array_collect[, , 1] <- cbind(post_mean_sem, post_sd_sem, t(post_q_sem)) dimnames(array_collect)[[3]] <- c("sem") dimnames(array_collect)[[2]] <- c("Post.mean", "Post.sd", "Cred.lb", "Creb.ub") coefs <- list(group = array_collect) # colnames(sem_summary)[3:4] <- c("Cred.lb", "Cred.ub") returned_object <- list(sem_summary = sem_summary, coefs = coefs) class(returned_object) <- c("sem", "list") } return(returned_object) } print.sem <- function(x, ...){ cat("Standard Error of Measurement\n\n") if(is(x, "list")){ cat("Fixed Effect:\n\n") print(as.data.frame(x$sem_summary), row.names = FALSE, digits = 3, right = FALSE) cat("\n") cat("------\n") cat("Group-Level:\n\n") print(as.data.frame(x$coefs$group[,,"sem"]), row.names = FALSE, digits = 3, right = FALSE) } else { print(as.data.frame(x), row.names = FALSE, digits = 3, right = FALSE) } cat("------") }
/scratch/gouwar.j/cran-all/cranData/vICC/R/sem.R
#' @title Varying Intraclass Correlation Coefficients #' #' @description Compute varying intraclass correlation coefficients with the method #' introduced in \insertCite{williams2019putting;textual}{vICC}. #' #' @param y Numeric vector. The outcome variable. #' #' @param group Numeric vector. The grouping variable (e.g., subjects). Note that the groups #' must be numbered from 1 to the total number of groups. #' See \code{\link[vICC]{change_group}}. #' #' @param type Character string. Which model should be fitted #' (defaults to \code{pick_group})? The options are #' described in \code{Details}. #' #' @param iter Numeric. The number of posterior samples per chain (excluding \code{burnin}). #' #' @param chains Numeric. The number of chains (defaults to \code{2}). #' #' @param burnin Numeric. The number of burnin samples, which are discarded #' (defaults to \code{500}). #' #' @param prior_scale Numeric. The prior distribution scale parameter #' (defaults to \code{1}). Note the prior is a #' half student-t distribution with 10 degrees of freedom. #' #' @param prior_prob Numeric. The prior inclusion probability (defaults to \code{0.5}). This #' is used for \code{type = "pick_tau"} or \code{type = "pick_group"} and ignored #' otherwise. #' #' @references #' \insertAllCited{} #' #' @return An object of class \code{vicc}. #' #' @importFrom rjags jags.model coda.samples #' #' @export #' #' @examples #' \donttest{ #' #' # congruent trials #' congruent <- subset(flanker, cond == 0) #' #' # subset 25 from each group #' dat <- congruent[unlist(tapply(1:nrow(congruent), #' congruent$id, #' head, 25)), ] #' #' # fit model #' fit <- vicc(y = dat$rt, #' group = dat$id, #' iter = 250, #' burnin = 10, #' type = "customary") #'} vicc <- function(y, group, type = "pick_group", iter = 5000, chains = 2, burnin = 500, prior_scale = 1, prior_prob = 0.5){ # outcome y <- y N <- length(y) # groups ID <- group # number of groups J <- length(unique(ID)) if(type == "pick_group") { model <- rjags::jags.model( file = base::textConnection(ICC_pick_id), n.chains = chains, inits = list(fe_mu = mean(y)), data = list( y = y, ID = ID, J = J, N = N, prior_scale = prior_scale, inc_prob = prior_prob ) ) fit <- rjags::coda.samples( model, n.iter = iter + burnin, variable.names = c( "fe_mu", "fe_sd", "tau_mu", "pick_id", "tau_sd", "beta_s", "beta_l", "rho12" ) ) } else if (type == "pick_tau"){ model <- rjags::jags.model( base::textConnection(ICC_pick_tau), n.chains = chains, inits = list(fe_mu = mean(y)), data = list( y = y, ID = ID, J = J, N = N, prior_scale = prior_scale, inc_prob = prior_prob ) ) # fit for motivating example fit <- coda.samples( model = model, n.iter = iter + burnin, variable.names = c( "fe_mu", "fe_sd", "tau_mu", "pick_tau", "tau_sd", "beta_s", "beta_l", "rho12" ) ) } else if(type == "pick_none"){ model <- rjags::jags.model( base::textConnection(ICC_lsm), n.chains = chains, inits = list(fe_mu = mean(y)), data = list( y = y, ID = ID, J = J, N = N, prior_scale = prior_scale ) ) fit <- rjags::coda.samples( model = model, n.iter = iter + burnin, variable.names = c("fe_mu", "fe_sd", "tau_mu", "tau_sd", "beta_s", "beta_l", "rho12") ) } else if(type == "customary"){ file <- textConnection(ICC_customary) model <- rjags::jags.model( file = file, n.chains = chains, inits = list(fe_mu = mean(y)), data = list( y = y, ID = ID, J = J, N = N, prior_scale = prior_scale ) ) fit <- rjags::coda.samples( model = model, n.iter = iter + burnin, variable.names = c("sigma", "beta", "tau_mu", "fe_mu") ) close(file) } else { stop("model not supported. see documentation") } returned_object <- list(fit = fit, type = type, model = model, chains = chains, iter = iter, burnin = burnin) class(returned_object) <- "vicc" return(returned_object) } #' Print \code{vicc} Objects #' #' @param x An object of class \code{vicc}. #' #' @param cred Numeric. Credible interval width (defaults to \code{0.90}). #' #' @param ... Currently ignored #' #' @export print.vicc <- function(x, cred = 0.95, ...){ lb <- (1 - cred) / 2 ub <- 1 - lb cat("vICC: Varying Intraclass Correlation Coefficients\n") # cat("-----\n") samps <- posterior_samples(x) if(x$type == "customary"){ cat("Type:", x$type, "\n") cat("-----\n") cat("Random Effects:\n") re_sd <- samps$tau_mu re_summary <- data.frame(Post.mean = mean(re_sd), Post.sd = sd(re_sd), t(quantile(re_sd, c(lb, ub)))) row.names(re_summary) <- "RE.sd.mean" colnames(re_summary)[3:4] <- c("Cred.lb", "Cred.ub") print(round(re_summary, 4), right = FALSE) cat("\n") obs_per_group <- tapply(x$model$data()$ID, x$model$data()$ID, length) icc1 <- (samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + samps$sigma ^ 2)) icc2 <- (samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + ((samps$sigma ^2) / mean(obs_per_group)))) cat("Fixed Effects:\n") fe_mu <- samps$fe_mu fe_summary <- rbind.data.frame( data.frame(Post.mean = mean(fe_mu), Post.sd = sd(fe_mu), t(quantile(fe_mu, c(lb, ub)))), data.frame(Post.mean = mean(icc1), Post.sd = sd(icc1), t(quantile(icc1, c(lb, ub)))), data.frame(Post.mean = mean(icc2), Post.sd = sd(icc2), t(quantile(icc2, c(lb, ub)))) ) row.names(fe_summary) <- c("FE.mean", "ICC(1)", "ICC(2)") colnames(fe_summary)[3:4] <- c("Cred.lb", "Cred.ub") print(round(fe_summary, 4), right = FALSE) sigma <- samps$sigma sigma_summary <- data.frame(Post.mean = mean(sigma), Post.sd = sd(sigma), t(quantile(sigma, c(lb, ub)))) row.names(sigma_summary) <- "sigma" colnames(sigma_summary)[3:4] <- c("Cred.lb", "Cred.ub") cat("\n") cat("Residual SD:\n") print(round(sigma_summary, 4), right = FALSE) } else { cat("Type:", x$type, "\n") cat("-----\n") cat("Random Effects:\n") re_sd_mean <- samps$tau_mu re_sd_sd <- samps$tau_sd re_cor <- samps$rho12 re_summary <- rbind.data.frame( data.frame(Post.mean = mean(re_sd_mean), Post.sd = sd(re_sd_mean), t(quantile(re_sd_mean, c(lb, ub)))), data.frame(Post.mean = mean(re_sd_sd), Post.sd = sd(re_sd_sd), t(quantile(re_sd_sd, c(lb, ub)))), data.frame(Post.mean = mean(re_cor), Post.sd = sd(re_cor), t(quantile(re_cor, c(lb, ub)))) ) row.names(re_summary) <- c("RE.sd.mean", "RE.sd.sigma", "Cor(mean,sigma)") colnames(re_summary)[3:4] <- c("Cred.lb", "Cred.ub") print(round(re_summary, 4), right = FALSE) cat("\n") cat("Fixed Effects:\n") fe_mu <- samps$fe_mu fe_sd <- exp(samps$fe_sd) obs_per_group <- tapply(x$model$data()$ID, x$model$data()$ID, length) icc1 <- (samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + exp(samps$fe_sd) ^ 2)) icc2 <- (samps$tau_mu ^ 2 / (samps$tau_mu ^ 2 + exp(samps$fe_sd)^2 / mean(obs_per_group))) fe_summary <- rbind.data.frame( data.frame(Post.mean = mean(fe_mu), Post.sd = sd(fe_mu), t(quantile(fe_mu, c(lb, ub)))), data.frame(Post.mean = mean(fe_sd), Post.sd = sd(fe_sd), t(quantile(fe_sd, c(lb, ub)))), data.frame(Post.mean = mean(icc1), Post.sd = sd(icc1), t(quantile(icc1, c(lb, ub)))), data.frame(Post.mean = mean(icc2), Post.sd = sd(icc2), t(quantile(icc2, c(lb, ub)))) ) row.names(fe_summary) <- c("FE.mean", "FE.sigma", "ICC(1)", "ICC(2)") colnames(fe_summary)[3:4] <- c("Cred.lb", "Cred.ub") print(round(fe_summary, 4), right = FALSE) } cat("-----\n") }
/scratch/gouwar.j/cran-all/cranData/vICC/R/vicc.R
#' @title Normalization constant of von Mises - Fisher distribution. #' #' @description \code{CpvMF} returns the normalization constant of von Mises - Fisher density. #' #' @details The probability density function of the von Mises - Fisher distribution is defined by : #' \deqn{f(z|theta) = C_p(|theta|)\exp{(z theta)}} #' \eqn{|theta|} is the intensity parameter and \eqn{\frac{theta}{|theta|}} the mean directional parameter. The normalization constant \eqn{C_p()} depends #' on the Bessel function of the first kind. See more details \href{https://en.wikipedia.org/wiki/Von_Mises-Fisher_distribution}{here}. #' #' @param p as sphere dimension. #' @param k as the intensity parameter. #' @return the normalization constant. #' @examples #' #' CpvMF(2,3.1) #' #' @keywords distribution #' @keywords directional statistics #' @keywords coordinates #' @keywords simulations #' @seealso #' \code{\link{rvMF}} and \code{\link{dvMF}} #' #' @references #' Wood, A. T. (1994). Simulation of the von Mises Fisher distribution. \emph{Communications in statistics-simulation and computation}, 23(1), 157-164. \doi{10.1080/03610919408813161}. #' @references #' Hornik, K., & Grun, B. (2014). \pkg{movMF}: An \R package for fitting mixtures of von Mises-Fisher distributions. \emph{Journal of Statistical Software}, 58(10), 1-31. \doi{10.18637/jss.v058.i10}. #' @importFrom Rcpp sourceCpp #' @export CpvMF <- function(p, k){ return(exp(logCpvMFcpp(p,k))) }
/scratch/gouwar.j/cran-all/cranData/vMF/R/CpvMF.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 cpprvMF <- function(size, theta) { .Call(`_vMF_cpprvMF`, size, theta) } logCpvMFcpp <- function(p, k) { .Call(`_vMF_logCpvMFcpp`, p, k) } dvMFcpp <- function(z, theta, logp = FALSE) { .Call(`_vMF_dvMFcpp`, z, theta, logp) }
/scratch/gouwar.j/cran-all/cranData/vMF/R/RcppExports.R
#' @title PDF of the von Mises - Fisher distribution. #' #' @description \code{dvMF} computes the density of the von Mises - Fisher distribution, given a set of spherical coordinates and the distribution parameters. #' #' @details The probability density function of the von Mises - Fisher distribution is defined by : #' \deqn{f(z|theta) = C_p(|theta|)\exp{(z theta)}} #' \eqn{|theta|} is the intensity parameter and \eqn{\frac{theta}{|theta|}} the mean directional parameter. The normalization constant \eqn{C_p()} depends #' on the Bessel function of the first kind. See more details \href{https://en.wikipedia.org/wiki/Von_Mises-Fisher_distribution}{here}. #' #' @param z as the set of points at which the spherical coordinate will be evaluated. z may be an one row matrix or vector if it contain one spherical coordinates or a #' matrix whose each row is one spherical coordinates. #' @param theta as the distribution parameter. #' @return the densities computed at each point #' @examples{} #' # Draw 1000 vectors from vM-F with parameter 1, (1,0) #' z <- rvMF(1000,c(1,0)) #' #' # Compute the density at these points #' dvMF(z,c(1,0)) #' #' # Density of (0,1,0,0) with the parameter 3, (0,1,0,0) #' dvMF(c(0,1,0,0),c(0,3,0,0)) #' @author #' Aristide Houndetoungan <\email{ariel92and@@gmail.com}> #' @keywords distribution #' @keywords directional statistics #' @keywords coordinates #' @keywords simulations #' @seealso #' \code{rvMF} and \code{\link{CpvMF}} #' #' @references #' Wood, A. T. (1994). Simulation of the von Mises Fisher distribution. \emph{Communications in statistics-simulation and computation}, 23(1), 157-164. \doi{10.1080/03610919408813161}. #' @references #' Hornik, K., & Grun, B. (2014). \pkg{movMF}: An \R package for fitting mixtures of von Mises-Fisher distributions. \emph{Journal of Statistical Software}, 58(10), 1-31. \doi{10.18637/jss.v058.i10}. #' @export dvMF <- function(z, theta){ if(inherits(z, "numeric")) z <- matrix(z, nrow = 1) return(as.vector(dvMFcpp(z,theta))) }
/scratch/gouwar.j/cran-all/cranData/vMF/R/dvMF.R
#' @title Sample from von Mises - Fisher distribution. #' #' @description \code{rvMF} returns random draws from von Mises - Fisher distribution. #' #' @details The parameter theta is such that \eqn{dim(theta)} is the sphere dimension, \eqn{|theta|} the intensity parameter and \eqn{\frac{theta}{|theta|}} the mean directional parameter. #' #' @param size as the number of draws needed. #' @param theta as the distribution parameter. #' @return A matrix whose each row is a random draw from the distribution. #' @examples #' # Draw 1000 vectors from vM-F with parameter 1, (1,0) #' rvMF(1000,c(1,0)) #' #' # Draw 10 vectors from vM-F with parameter sqrt(14), (2,1,3) #' rvMF(10,c(2,1,3)) #' #' # Draw from the vMF distribution with mean direction proportional #' # to c(1, -1) and concentration parameter 3 #' rvMF(10, 3 * c(1, -1) / sqrt(2)) #' #' @keywords distribution #' @keywords directional statistics #' @keywords coordinates #' @keywords simulations #' @references #' Wood, A. T. (1994). Simulation of the von Mises Fisher distribution. \emph{Communications in statistics-simulation and computation}, 23(1), 157-164. \doi{10.1080/03610919408813161}. #' @references #' Hornik, K., & Grun, B. (2014). \pkg{movMF}: An \R package for fitting mixtures of von Mises-Fisher distributions. \emph{Journal of Statistical Software}, 58(10), 1-31. \doi{10.18637/jss.v058.i10}. #' @export rvMF <- function(size, theta){ return(cpprvMF(size,theta)) }
/scratch/gouwar.j/cran-all/cranData/vMF/R/rvMF.R
#' @title Sample from von Mises - Fisher distribution #' #' @description vMF samples from von Mises-Fisher distribution and performs some operations. #' Unlike the \href{https://cran.r-project.org/package=movMF}{movMF} package, vMF does not consider mixtures of von Mises-Fisher distribution. #' vFM particularly focuses on sampling from the distribution and performs it very quickly. This is useful to carry out fast simulations in directional statistics. #' vMF also computes the density and normalization constant of the von Mises-Fisher distribution. #' #' #' @author #' Aristide Houndetoungan <\email{ariel92and@@gmail.com}> #' #' @references #' Wood, A. T. (1994). Simulation of the von Mises Fisher distribution. \emph{Communications in statistics-simulation and computation}, 23(1), 157-164. \doi{10.1080/03610919408813161}. #' @references #' Hornik, K., & Grun, B. (2014). \pkg{movMF}: An \R package for fitting mixtures of von Mises-Fisher distributions. \emph{Journal of Statistical Software}, 58(10), 1-31. \doi{10.18637/jss.v058.i10}. #' @useDynLib vMF, .registration = TRUE "_PACKAGE" NULL
/scratch/gouwar.j/cran-all/cranData/vMF/R/vMF.R
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----comp1, echo = TRUE, eval = TRUE------------------------------------------ library(vMF) library(movMF) n <- 5 # Number of draws set.seed(123) xvMF <- rvMF(n,c(1,0,0)) set.seed(123) xmovMF <- rmovMF(n,c(1,0,0)) all.equal(c(xvMF), c(xmovMF)) xvMF xmovMF ## ----comp2, echo = TRUE, eval = TRUE------------------------------------------ n <- 30 set.seed(123) ddpcr::quiet(runif(n)) xvMF <- rvMF(n,c(1,0,0)) set.seed(123) xmovMF <- rmovMF(n,c(1,0,0)) all.equal(c(xvMF), c(xmovMF)) xvMF[1:5,] xmovMF[1:5,] ## ----ex1, echo = TRUE, eval = TRUE-------------------------------------------- library(rbenchmark) fcompare <- function(n) { benchmark("vMF" = rvMF(n,c(1,0,0)), "movMF" = rmovMF(1,c(1,0,0))) } fcompare(1) fcompare(10) fcompare(100) ## ----ex11a, echo = FALSE, eval = TRUE----------------------------------------- #load data to save time during the building load("out.Rdata") ## ----ex11b, echo = TRUE, eval = FALSE----------------------------------------- # out <- unlist(lapply(1:200, function(x) fcompare(x)$elapsed[1]/fcompare(x)$elapsed[2])) ## ----ex11c, echo = TRUE, eval = TRUE, fig.height = 4, fig.align = "center"---- library(ggplot2) ggplot(data = data.frame(n = 1:200, time = out), aes(x = n, y = time)) + geom_point(col = "blue") + geom_hline(yintercept = 1, col = 2) ## ----ex2a, echo = TRUE, eval = FALSE------------------------------------------ # set.seed(123) # P <- 4 # initial <- rmovMF(1, rep(0, P)) # # Fonction based on vMF to simulate theta # SamplevMF <- function(n) { # output <- matrix(0, n + 1, P) # output[1, ] <- initial # for (i in 1:n) { # output[i + 1,] <- rvMF(1, output[i,]) # } # return(output) # } # # # Fonction based on movMF to simulate theta # SamplemovMF <-function(n){ # output <- matrix(0, n + 1, P) # output[1, ] <- initial # for (i in 1:n) { # output[i + 1,] <- rmovMF(1, output[i,]) # } # return(output) # } # benchmark("vMF" = SamplevMF(1000), "movMF" = SamplemovMF(1000)) ## ----ex2b, echo = FALSE, eval = TRUE------------------------------------------ print(outbench)
/scratch/gouwar.j/cran-all/cranData/vMF/inst/doc/vMF.R
--- title: "An R Package for Fast Sampling from von Mises Fisher Distribution" author: "Aristide Houndetoungan" date: "`r Sys.Date()`" output: pdf_document: citation_package: natbib number_sections: true bookdown::pdf_book: citation_package: biblatex bibliography: ["References.bib", "Packages.bib"] biblio-style: "apalike" link-citations: true urlcolor: blue vignette: > %\VignetteIndexEntry{An R Package for Fast Sampling from von Mises Fisher Distribution} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- <style> body { text-align: justify} </style> ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Introduction{-#over} The package **vMF** simulates von Mises-Fisher distribution ($\mathcal{M}$). Unlike the package [**movMF**](https://CRAN.R-project.org/package=movMF) [@hornik2014movmf], which simulates and estimates mixtures of $\mathcal{M}$, **vFM** performs fast sampling as its source code is written in C++. **vFM** also computes the density and the normalization constant of $\mathcal{M}$. The von Mises-Fisher distribution is used to model coordinates on a hypersphere of dimension $p \ge 2$. Roughly speaking, it is the equivalent of the normal distribution on a hypersphere. As the normal distribution, $\mathcal{M}$ is characterized by two parameters. The location (or mean directional) parameter $\boldsymbol{\mu}$ around which draws will be concentrated and the intensity parameter $\eta$ which measures the intensity of concentration of the draws around $\boldsymbol{\mu}$. The higher $\eta$, the more the draws are concentrated around $\boldsymbol{\mu}$. Compared to the normal distribution, $\boldsymbol{\mu}$ is similar to the mean parameter of the normal distribution and $1/\eta$ is similar to the standard deviation. There are several definitions of the density function of $\mathcal{M}$. In this package, the density is normalized by the uniform distribution without loss of generality. This is also the case in @mardia2009directional and @hornik2013conjugate. Let $\mathbf{z} \sim \mathcal{M}\left(\eta,\boldsymbol{\mu}\right)$. The density of $\mathbf{z}$ is given by $$f_p(\mathbf{z}|\eta, \boldsymbol{\mu}) =C_p(\eta) e^{\eta\mathbf{z}'\boldsymbol{\mu}},$$ where $\displaystyle C_p(x) = \left(\frac{x}{2}\right)^{\frac{p}{2}-1}\frac{1}{\Gamma\left(\frac{p}{2}\right)I_{\frac{p}{2}-1}(x)}$ is the normalization constant and $I_.(.)$ the Bessel function of the first kind defined by: $$\displaystyle I_{\alpha}(x) = \sum_{m=0}^{\infty}\frac{\left(\frac{x}{2}\right)^{2m+\alpha}}{m!\Gamma(m+\alpha + 1)}.$$ \noindent The normalization with respect to the uniform distribution implies $C_p(0)=1$. # Simulation from von Mises Fisher distribution{-#sim} The following algorithm provides a rejection sampling scheme for drawing a sample from $\mathcal{M}$ with mean directional parameter $\boldsymbol{\mu} = (0, ... , 0, 1)$ and concentration (intensity) parameter $\eta \ge 0$ [see Section 2.1 in @hornik2014movmf]. * Step 1. Calculate $b$ using * Step 1. Calculate $b$ using $$b = \dfrac{p - 1}{2\eta + \sqrt{2\eta^2 + (p - 1)^2}}.$$ Let $x_0 = (1 - b)/(1 + b)$ and $c = \eta x_0 + (p - 1)\log\left(1 - x_0^2\right)$. * Step 2. Generate $Z \sim Beta((p-1)/2,(p-1)/2)$ and $U \sim Unif([0, 1])$ and calculate $$W = \dfrac{1-(1+b)Z}{1-(1-b)Z}.$$ * Step 3. If $$\eta W+(p-1)\log(1-x_0W)-c<\log(U),$$ go to step 2. * Step 4. Generate a uniform $(d-1)$-dimensional unit vector $\mathbf{V}$ and return $$\mathbf{X} =\left(\sqrt{1- W^2}\mathbf{V}^{\prime},W\right)^{\prime}$$ The uniform ($d-1$)-dimensional unit vector $\mathbf{V}$ can be generated by simulating $d-1$ independent standard normal random variables and normalizing them so as $\lVert \mathbf{V} \rVert_2 = 1$. To get sampling from $\mathcal{M}$ with arbitrary mean direction parameter $\boldsymbol{\mu}$, $\mathbf{X}$ is multiplied from the left with a matrix where the first $d-1$ columns consist of unitary basis vectors of the subspace orthogonal to $\boldsymbol{\mu}$ and the last column is equal to $\boldsymbol{\mu}$. # Comparison of vMF and movMF{-#comp} In this section, I compare **vMF** and **[movMF](https://CRAN.R-project.org/package=movMF)**. <!--First, I compare draws from both packages to make sure that they are the same. ```{r comp1, echo = TRUE, eval = TRUE} library(vMF) library(movMF) n <- 5 # Number of draws set.seed(123) xvMF <- rvMF(n,c(1,0,0)) set.seed(123) xmovMF <- rmovMF(n,c(1,0,0)) all.equal(c(xvMF), c(xmovMF)) xvMF xmovMF ``` The outputs are surprisingly different although the random number generators are fixed. After studying the source code of **[movMF](https://CRAN.R-project.org/package=movMF)**, I notice that the two packages do not code their sampling function in the same way. The function `rmovMF` is more general and is designed to draw samples from a mixture of $\mathcal{M}$. The sampling function first generates $n$ (the sample size) random numbers from the uniform distribution before running the algorithm described above. This simulation modifies the random number generators. One can then obtain the same output by first simulating $n$ numbers from the uniform distribution before calling the function `rvMF`. ```{r comp2, echo = TRUE, eval = TRUE} n <- 30 set.seed(123) ddpcr::quiet(runif(n)) xvMF <- rvMF(n,c(1,0,0)) set.seed(123) xmovMF <- rmovMF(n,c(1,0,0)) all.equal(c(xvMF), c(xmovMF)) xvMF[1:5,] xmovMF[1:5,] ``` I now compare the performance of both packages.--> ```{r ex1, echo = TRUE, eval = TRUE} library(rbenchmark) fcompare <- function(n) { benchmark("vMF" = rvMF(n,c(1,0,0)), "movMF" = rmovMF(1,c(1,0,0))) } fcompare(1) fcompare(10) fcompare(100) ``` **vMF** performs over **[movMF](https://CRAN.R-project.org/package=movMF)**. The performance of **vMF** is much better when only few simulations are performed. When the sample is too large, the two package require approximately the same running time. ```{r ex11a, echo = FALSE, eval = TRUE} #load data to save time during the building load("out.Rdata") ``` ```{r ex11b, echo = TRUE, eval = FALSE} out <- unlist(lapply(1:200, function(x) fcompare(x)$elapsed[1]/fcompare(x)$elapsed[2])) ``` ```{r ex11c, echo = TRUE, eval = TRUE, fig.height = 4, fig.align = "center"} library(ggplot2) ggplot(data = data.frame(n = 1:200, time = out), aes(x = n, y = time)) + geom_point(col = "blue") + geom_hline(yintercept = 1, col = 2) ``` Many papers use simulations from the von-Mises Fisher distribution in a Markov Chain Monte Carlo (MCMC) process. A single draw is performed at each iteration of the MCMC. This is for example the case in @boucher2019partial, @breza2020using, @mccormick2015latent. In such a simulation context, using **vMF** would take much less time than **[movMF](https://CRAN.R-project.org/package=movMF)**. For example, I consider the process $\left(\mathbf{z}_t\right)_{t\in\mathbb{N}}$ which follows a random walk of the von-Mises Fisher distribution. The first variable, $\mathbf{z}_0$, is randowmly set on a 4-dimensional hypersphere and $\mathbf{z}_t \sim \mathcal{M}\left(1,\mathbf{z} _ {t - 1}\right)$ $\forall$ $t > 0$. Simulating this process has about the same complexity as using von-Mises Fisher drawings in an MCMC. ```{r ex2a, echo = TRUE, eval = FALSE} set.seed(123) P <- 4 initial <- rmovMF(1, rep(0, P)) # Fonction based on vMF to simulate theta SamplevMF <- function(n) { output <- matrix(0, n + 1, P) output[1, ] <- initial for (i in 1:n) { output[i + 1,] <- rvMF(1, output[i,]) } return(output) } # Fonction based on movMF to simulate theta SamplemovMF <-function(n){ output <- matrix(0, n + 1, P) output[1, ] <- initial for (i in 1:n) { output[i + 1,] <- rmovMF(1, output[i,]) } return(output) } benchmark("vMF" = SamplevMF(1000), "movMF" = SamplemovMF(1000)) ``` ```{r ex2b, echo = FALSE, eval = TRUE} print(outbench) ``` The comparison of the running times **vMF** is less time-consuming
/scratch/gouwar.j/cran-all/cranData/vMF/inst/doc/vMF.Rmd
--- title: "An R Package for Fast Sampling from von Mises Fisher Distribution" author: "Aristide Houndetoungan" date: "`r Sys.Date()`" output: pdf_document: citation_package: natbib number_sections: true bookdown::pdf_book: citation_package: biblatex bibliography: ["References.bib", "Packages.bib"] biblio-style: "apalike" link-citations: true urlcolor: blue vignette: > %\VignetteIndexEntry{An R Package for Fast Sampling from von Mises Fisher Distribution} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- <style> body { text-align: justify} </style> ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Introduction{-#over} The package **vMF** simulates von Mises-Fisher distribution ($\mathcal{M}$). Unlike the package [**movMF**](https://CRAN.R-project.org/package=movMF) [@hornik2014movmf], which simulates and estimates mixtures of $\mathcal{M}$, **vFM** performs fast sampling as its source code is written in C++. **vFM** also computes the density and the normalization constant of $\mathcal{M}$. The von Mises-Fisher distribution is used to model coordinates on a hypersphere of dimension $p \ge 2$. Roughly speaking, it is the equivalent of the normal distribution on a hypersphere. As the normal distribution, $\mathcal{M}$ is characterized by two parameters. The location (or mean directional) parameter $\boldsymbol{\mu}$ around which draws will be concentrated and the intensity parameter $\eta$ which measures the intensity of concentration of the draws around $\boldsymbol{\mu}$. The higher $\eta$, the more the draws are concentrated around $\boldsymbol{\mu}$. Compared to the normal distribution, $\boldsymbol{\mu}$ is similar to the mean parameter of the normal distribution and $1/\eta$ is similar to the standard deviation. There are several definitions of the density function of $\mathcal{M}$. In this package, the density is normalized by the uniform distribution without loss of generality. This is also the case in @mardia2009directional and @hornik2013conjugate. Let $\mathbf{z} \sim \mathcal{M}\left(\eta,\boldsymbol{\mu}\right)$. The density of $\mathbf{z}$ is given by $$f_p(\mathbf{z}|\eta, \boldsymbol{\mu}) =C_p(\eta) e^{\eta\mathbf{z}'\boldsymbol{\mu}},$$ where $\displaystyle C_p(x) = \left(\frac{x}{2}\right)^{\frac{p}{2}-1}\frac{1}{\Gamma\left(\frac{p}{2}\right)I_{\frac{p}{2}-1}(x)}$ is the normalization constant and $I_.(.)$ the Bessel function of the first kind defined by: $$\displaystyle I_{\alpha}(x) = \sum_{m=0}^{\infty}\frac{\left(\frac{x}{2}\right)^{2m+\alpha}}{m!\Gamma(m+\alpha + 1)}.$$ \noindent The normalization with respect to the uniform distribution implies $C_p(0)=1$. # Simulation from von Mises Fisher distribution{-#sim} The following algorithm provides a rejection sampling scheme for drawing a sample from $\mathcal{M}$ with mean directional parameter $\boldsymbol{\mu} = (0, ... , 0, 1)$ and concentration (intensity) parameter $\eta \ge 0$ [see Section 2.1 in @hornik2014movmf]. * Step 1. Calculate $b$ using * Step 1. Calculate $b$ using $$b = \dfrac{p - 1}{2\eta + \sqrt{2\eta^2 + (p - 1)^2}}.$$ Let $x_0 = (1 - b)/(1 + b)$ and $c = \eta x_0 + (p - 1)\log\left(1 - x_0^2\right)$. * Step 2. Generate $Z \sim Beta((p-1)/2,(p-1)/2)$ and $U \sim Unif([0, 1])$ and calculate $$W = \dfrac{1-(1+b)Z}{1-(1-b)Z}.$$ * Step 3. If $$\eta W+(p-1)\log(1-x_0W)-c<\log(U),$$ go to step 2. * Step 4. Generate a uniform $(d-1)$-dimensional unit vector $\mathbf{V}$ and return $$\mathbf{X} =\left(\sqrt{1- W^2}\mathbf{V}^{\prime},W\right)^{\prime}$$ The uniform ($d-1$)-dimensional unit vector $\mathbf{V}$ can be generated by simulating $d-1$ independent standard normal random variables and normalizing them so as $\lVert \mathbf{V} \rVert_2 = 1$. To get sampling from $\mathcal{M}$ with arbitrary mean direction parameter $\boldsymbol{\mu}$, $\mathbf{X}$ is multiplied from the left with a matrix where the first $d-1$ columns consist of unitary basis vectors of the subspace orthogonal to $\boldsymbol{\mu}$ and the last column is equal to $\boldsymbol{\mu}$. # Comparison of vMF and movMF{-#comp} In this section, I compare **vMF** and **[movMF](https://CRAN.R-project.org/package=movMF)**. <!--First, I compare draws from both packages to make sure that they are the same. ```{r comp1, echo = TRUE, eval = TRUE} library(vMF) library(movMF) n <- 5 # Number of draws set.seed(123) xvMF <- rvMF(n,c(1,0,0)) set.seed(123) xmovMF <- rmovMF(n,c(1,0,0)) all.equal(c(xvMF), c(xmovMF)) xvMF xmovMF ``` The outputs are surprisingly different although the random number generators are fixed. After studying the source code of **[movMF](https://CRAN.R-project.org/package=movMF)**, I notice that the two packages do not code their sampling function in the same way. The function `rmovMF` is more general and is designed to draw samples from a mixture of $\mathcal{M}$. The sampling function first generates $n$ (the sample size) random numbers from the uniform distribution before running the algorithm described above. This simulation modifies the random number generators. One can then obtain the same output by first simulating $n$ numbers from the uniform distribution before calling the function `rvMF`. ```{r comp2, echo = TRUE, eval = TRUE} n <- 30 set.seed(123) ddpcr::quiet(runif(n)) xvMF <- rvMF(n,c(1,0,0)) set.seed(123) xmovMF <- rmovMF(n,c(1,0,0)) all.equal(c(xvMF), c(xmovMF)) xvMF[1:5,] xmovMF[1:5,] ``` I now compare the performance of both packages.--> ```{r ex1, echo = TRUE, eval = TRUE} library(rbenchmark) fcompare <- function(n) { benchmark("vMF" = rvMF(n,c(1,0,0)), "movMF" = rmovMF(1,c(1,0,0))) } fcompare(1) fcompare(10) fcompare(100) ``` **vMF** performs over **[movMF](https://CRAN.R-project.org/package=movMF)**. The performance of **vMF** is much better when only few simulations are performed. When the sample is too large, the two package require approximately the same running time. ```{r ex11a, echo = FALSE, eval = TRUE} #load data to save time during the building load("out.Rdata") ``` ```{r ex11b, echo = TRUE, eval = FALSE} out <- unlist(lapply(1:200, function(x) fcompare(x)$elapsed[1]/fcompare(x)$elapsed[2])) ``` ```{r ex11c, echo = TRUE, eval = TRUE, fig.height = 4, fig.align = "center"} library(ggplot2) ggplot(data = data.frame(n = 1:200, time = out), aes(x = n, y = time)) + geom_point(col = "blue") + geom_hline(yintercept = 1, col = 2) ``` Many papers use simulations from the von-Mises Fisher distribution in a Markov Chain Monte Carlo (MCMC) process. A single draw is performed at each iteration of the MCMC. This is for example the case in @boucher2019partial, @breza2020using, @mccormick2015latent. In such a simulation context, using **vMF** would take much less time than **[movMF](https://CRAN.R-project.org/package=movMF)**. For example, I consider the process $\left(\mathbf{z}_t\right)_{t\in\mathbb{N}}$ which follows a random walk of the von-Mises Fisher distribution. The first variable, $\mathbf{z}_0$, is randowmly set on a 4-dimensional hypersphere and $\mathbf{z}_t \sim \mathcal{M}\left(1,\mathbf{z} _ {t - 1}\right)$ $\forall$ $t > 0$. Simulating this process has about the same complexity as using von-Mises Fisher drawings in an MCMC. ```{r ex2a, echo = TRUE, eval = FALSE} set.seed(123) P <- 4 initial <- rmovMF(1, rep(0, P)) # Fonction based on vMF to simulate theta SamplevMF <- function(n) { output <- matrix(0, n + 1, P) output[1, ] <- initial for (i in 1:n) { output[i + 1,] <- rvMF(1, output[i,]) } return(output) } # Fonction based on movMF to simulate theta SamplemovMF <-function(n){ output <- matrix(0, n + 1, P) output[1, ] <- initial for (i in 1:n) { output[i + 1,] <- rmovMF(1, output[i,]) } return(output) } benchmark("vMF" = SamplevMF(1000), "movMF" = SamplemovMF(1000)) ``` ```{r ex2b, echo = FALSE, eval = TRUE} print(outbench) ``` The comparison of the running times **vMF** is less time-consuming
/scratch/gouwar.j/cran-all/cranData/vMF/vignettes/vMF.Rmd
#' VA CVD Risk Score (2021) #' #' Calculates the cardiovascular (CVD) risk score for women military service #' members and veterans. #' #' @param age Patient age (years: 1-110) #' @param race Patient race (1 = White, 2 = African American, 3 = Hispanic) #' @param TC Total cholesterol (mg/dL: 0-400) #' @param HDL HDL cholesterol (mg/dL: 0-200) #' @param SBP Systolic blood pressure (mmHg: 0-300) #' @param SBPTrt Patient is on a blood pressure medication (1 = Yes, 0 = No) #' @param Smoke Current smoker (1 = Yes, 0 = No) #' @param DM Diabetes (1 = Yes, 0 = No) #' @param Depression Major Depression (1 = Yes, 0 = No) #' @param verbose logical: should input (patient profile) be printed. #' #' @return Estimated 10-year CVD Risk for VA women military service #' members and veterans. #' #' @export #' #' @examples #' library(vaRiskScore) #' vaScore(age = 50, #' race = 1, #' SBPTrt = 1, #' SBP = 150, #' TC = 100, #' HDL = 50, #' DM = 1, #' Smoke = 1, #' Depression = 1, #' verbose = TRUE) #' @references #'Jeon‐Slaughter, H., Chen, X., Tsai, S., Ramanan, B., & Ebrahimi, R. (2021). #'Developing an internally validated veterans affairs women cardiovascular #'disease risk score using Veterans Affairs National Electronic Health Records. #'Journal of the American Heart Association, 10(5), e019217. #' @author #' Xiaofei Chen; Haekyung Jeon‐Slaughter vaScore <- function(age = 50, race = 1, SBPTrt = 1, SBP = 150, TC = 100, HDL = 50, DM = 1, Smoke = 1, Depression = 1, verbose = TRUE) { # race: 1=White, 2=African American; 3=Hispanic. # SBPTrt: 1=Yes; 2=No; same for others. x_age = age * 12 x_lnage = log(x_age) x_lnagesq = x_lnage ^ 2 x_race = race x_SBPTrt = SBPTrt x_SBP = SBP x_lnSBP = log(x_SBP) x_TC = TC x_lnTC = log(x_TC) x_HDL = HDL x_lnHDL = log(x_HDL) x_DM = DM x_SMK = Smoke x_Dep = Depression if (age <= 0 | age >= 110 | SBP <= 0 | SBP >= 300 | TC < 0 | TC >= 400 | HDL <= 0 | HDL >= 200 | !race %in% c(1:3) | !SBPTrt %in% c(0, 1) | !DM %in% c(0, 1) | !Smoke %in% c(0, 1) | !Depression %in% c(0, 1)) { return('Please double check input (see manual for allowable values)!') } if (x_race == 1) { Mlnage = log(47.27 * 12) Mlnagesq = Mlnage ^ 2 MlnTotChol = log(198.63) MlnHDL = log(53.48) MlnBP = log(124.69) tmp <- exp( 2.399 * x_lnage + 0.024 * x_lnTC - 1.350 * x_lnHDL - 0.208 * x_lnSBP * x_SBPTrt + 1.008 * x_lnSBP + 0.072 * x_SMK + 0.425 * x_DM + 0.244 * x_Dep + 1.263 * x_SBPTrt - ( 2.399 * Mlnage + 0.024 * MlnTotChol - 1.350 * MlnHDL + 1.008 * MlnBP ) ) getRisk = 1 - 0.9438 ^ tmp raceCat = "White" } if (x_race == 2) { Mlnage = log(45.49 * 12) Mlnagesq = Mlnage ^ 2 MlnTotChol = log(192.09) MlnHDL = log(56.69) MlnBP = log(128.02) tmp <- exp( 2.058 * x_lnage + 0.180 * x_lnTC - 1.339 * x_lnHDL + 1.246 * x_lnSBP * (x_SBPTrt) + 0.411 * x_lnSBP - 0.020 * (x_SMK) + 0.276 * (x_DM) + 0.231 * (x_Dep) - 5.795 * (x_SBPTrt) - ( 2.058 * Mlnage + 0.180 * MlnTotChol - 1.339 * MlnHDL + 0.411 * MlnBP ) ) getRisk = 1 - 0.9442 ^ tmp raceCat = "African American" } if (x_race == 3) { Mlnage = log(44.64 * 12) Mlnagesq = Mlnage ^ 2 MlnTotChol = log(195.47) MlnHDL = log(53.85) MlnBP = log(123.39) tmp <- exp( 2.191 * x_lnage + 0.099 * x_lnTC - 1.225 * x_lnHDL - 3.714 * x_lnSBP * (x_SBPTrt) + 0.653 * x_lnSBP + 0.356 * (x_SMK) + 0.315 * (x_DM) + 0.311 * (x_Dep) + 18.290 * (x_SBPTrt) - ( 2.191 * Mlnage + 0.099 * MlnTotChol - 1.225 * MlnHDL + 0.653 * MlnBP ) ) getRisk = 1 - 0.9542 ^ tmp raceCat = "Hispanic" } getRisk = round(getRisk * 100, 2) risk_score = paste0("The predicted 10-year ASCVD risk is ", getRisk, "%") if (verbose) { cat("++++++++++++++++++++++++++++++++++++++++++++++++++", "\n") cat("Input:", "\n") cat(paste("Age (year):", age), "\n") cat(paste("Race:", raceCat), "\n") cat(paste("Systolic blood pressure (mmHg):", SBP), "\n") cat(paste("Total cholesterol (mg/dL):", TC), "\n") cat(paste("HDL cholesterol (mg/dL):", HDL), "\n") cat(paste("Blood pressure treatment:", ifelse(SBPTrt == 1, 'Yes', 'No')), "\n") cat(paste("Diabetes:", ifelse(DM == 1, 'Yes', 'No')), "\n") cat(paste("Current smoker:", ifelse(Smoke == 1, 'Yes', 'No')), "\n") cat(paste("Major depression:", ifelse(Depression == 1, 'Yes', 'No')), "\n") cat("++++++++++++++++++++++++++++++++++++++++++++++++++", "\n") cat("Result:", "\n") cat(risk_score) return(getRisk/100) } else{ return(getRisk/100) } }
/scratch/gouwar.j/cran-all/cranData/vaRiskScore/R/vaScore.R
#' Run diagnostics #' #' @description Run a set of diagnostic plots. Note that for this function to #' work, \code{\link{est_ce}} must be run with \code{return_extras=T}. #' @param obj An object of class \code{vaccine_est} returned by #' \code{\link{est_ce}} #' @return A combined plot of model diagnostics #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_np <- est_ce(dat=dat, type="NP", t_0=578, return_extras=TRUE) #' diagnostics(ests_np) #' } #' @export diagnostics <- function(obj) { # To prevent R CMD CHECK notes s <- est <- ind <- NULL; rm(s,est,ind); if (!methods::is(obj,"vaccine_est")) { stop(paste0("`obj` must be an object of class 'vaccine_est' returned by es", "t_ce().")) } p1 <- ggplot2::ggplot(obj$extras$r_Mn, ggplot2::aes(x=s, y=est)) + ggplot2::geom_line(color="#56B4E9") + ggplot2::geom_point(color="#56B4E9", size=1) + ggplot2::labs(y="", x="log(S)", title="r_Mn") p2 <- ggplot2::ggplot(obj$extras$deriv_r_Mn, ggplot2::aes(x=s, y=est)) + ggplot2::geom_line(color="#56B4E9") + ggplot2::geom_point(color="#56B4E9", size=1) + ggplot2::labs(y="", x="log(S)", title="deriv_r_Mn") p3 <- ggplot2::ggplot(obj$extras$Gamma_os_n, ggplot2::aes(x=s, y=est)) + ggplot2::geom_line(color="#56B4E9") + ggplot2::geom_point(color="#56B4E9", size=1) + ggplot2::labs(y="", x="log(S)", title="Gamma_os_n") p4 <- ggplot2::ggplot(obj$extras$f_s_n, ggplot2::aes(x=s, y=est)) + ggplot2::geom_line(color="#56B4E9") + ggplot2::geom_point(color="#56B4E9", size=1) + ggplot2::labs(y="", x="log(S)", title="f_s_n") p5 <- ggplot2::ggplot( obj$extras$Q_n, ggplot2::aes(x=t, y=est, group=factor(interaction(ind,s)), color=factor(s)) ) + ggplot2::geom_line(alpha=0.5) + ggplot2::facet_wrap(~s) + ggplot2::labs(y="", title="Q_n", color="s") + ggplot2::theme(legend.position="none") p6 <- ggplot2::ggplot( obj$extras$Qc_n, ggplot2::aes(x=t, y=est, group=factor(interaction(ind,s)), color=factor(s)) ) + ggplot2::geom_line(alpha=0.5) + ggplot2::facet_wrap(~s) + ggplot2::labs(y="", title="Qc_n", color="s") + ggplot2::theme(legend.position="none") plot <- ggpubr::ggarrange(plotlist=list(p5,p1,p2,p6,p3,p4), ncol=3, nrow=2) return(plot) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/diagnostics.R
#' Estimate controlled effect curves #' #' @description Estimate controlled risk (CR) curves and/or controlled vaccine #' efficacy (CVE) curves. See references for definitions of these curves. #' @param dat A data object returned by load_data #' @param type One of c("Cox", "NP"). This specifies whether to estimate the #' curve(s) using a marginalized Cox proportional hazards model or using a #' monotone-constrained nonparametric estimator. #' @param t_0 Time point of interest #' @param cr Boolean. If TRUE, the controlled risk (CR) curve is computed and #' returned. #' @param cve Boolean. If TRUE, the controlled vaccine efficacy (CVE) curve is #' computed and returned. #' @param s_out A numeric vector of s-values (on the biomarker scale) for which #' cve(s) and/or cr(s) are computed. Defaults to a grid of 101 points #' between the min and max biomarker values. #' @param ci_type One of c("transformed", "truncated", "regular", "none"). If #' ci_type="transformed", confidence intervals are computed on the logit(CR) #' and/or log(1-CVE) scale to ensure that confidence limits lie within [0,1] #' for CR and/or lie within (-inf,1] for CVE. If ci_type="truncated", #' confidence limits are constructed on the CR and/or CVE scale but #' truncated to lie within [0,1] for CR and/or lie within (-inf,1] for CVE. #' If ci_type="regular", confidence limits are not transformed or truncated. #' If ci_type="none", confidence intervals are not computed. #' @param placebo_risk_method One of c("KM", "Cox"). Method for estimating #' overall risk in the placebo group. "KM" computes a Kaplan-Meier estimate #' and "Cox" computes an estimate based on a marginalized Cox model survival #' curve. Only relevant if cve=TRUE. #' @param return_p_value Boolean; if TRUE, a P-value corresponding to the null #' hypothesis that the CVE curve is flat is returned. The type of P-value #' corresponds to the \code{type} argument. #' @param return_extras Boolean; if TRUE, objects useful for debugging are #' returned. #' @param params_cox A list of options returned by #' \code{\link{params_ce_cox}} that are relevant if type="Cox". #' @param params_np A list of options returned by \code{\link{params_ce_np}} #' that are relevant if type="NP". #' @return A list of the form \code{list(cr=list(...), cve=list(...))} #' containing CR and/or CVE estimates. Each of the inner lists contains the #' following: \itemize{ #' \item{\code{s}: a vector of marker values corresponding to s_out} #' \item{\code{est}: a vector of point estimates} #' \item{\code{ci_lower}: a vector of confidence interval lower limits} #' \item{\code{ci_upper}: a vector of confidence interval upper limits} #' } #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_cox <- est_ce(dat=dat, type="Cox", t_0=578) #' ests_np <- est_ce(dat=dat, type="NP", t_0=578) #' } #' @references Gilbert P, Fong Y, Kenny A, and Carone, M (2022). A Controlled #' Effects Approach to Assessing Immune Correlates of Protection. #' <doi:10.1093/biostatistics/kxac024> #' @export est_ce <- function( dat, type="Cox", t_0, cr=TRUE, cve=FALSE, s_out=seq(from=min(dat$s,na.rm=TRUE), to=max(dat$s,na.rm=TRUE), l=101), ci_type="transformed", placebo_risk_method="KM", return_p_value=FALSE, return_extras=FALSE, params_cox=params_ce_cox(), params_np=params_ce_np() ) { if (!methods::is(dat,"vaccine_dat")) { stop(paste0("`dat` must be an object of class 'vaccine_dat' returned by lo", "ad_data().")) } if (!(attr(dat, "groups") %in% c("vaccine", "both"))) { stop("Vaccine group data not detected.") } if (type=="Cox") { ests <- est_cox( dat=dat, t_0=t_0, cr=cr, cve=cve, s_out=s_out, ci_type=ci_type, placebo_risk_method=placebo_risk_method, return_p_value=return_p_value, return_extras=return_extras, spline_df=params_cox$spline_df, spline_knots=params_cox$spline_knots, edge_ind=params_cox$edge_ind ) } if (type=="NP") { ests <- est_np( dat=dat, t_0=t_0, cr=cr, cve=cve, s_out=s_out, ci_type=ci_type, placebo_risk_method=placebo_risk_method, return_p_value=return_p_value, return_extras=return_extras, params=params_np, cf_folds=1 ) } class(ests) <- "vaccine_est" return(ests) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/est_ce.R
#' Estimate CVE/CR using Cox model #' #' @description See docs for est_ce and params_ce_cox #' @noRd est_cox <- function( dat, t_0, cr, cve, s_out, ci_type, placebo_risk_method, return_p_value, return_extras, spline_df, spline_knots, edge_ind, p_val_only=FALSE ) { if (any(is.na(s_out))) { stop("NA values not allowed in s_out.") } # Create filtered data objects dat_v <- dat[dat$a==1,] dat_p <- dat[dat$a==0,] # Create spline basis and function dat_v_spl <- data.frame("s1"=dat_v$s) basic_cox_model <- F if ((!is.na(spline_df) && spline_df!=1) || !is.na(spline_knots[[1]])) { if (!is.na(spline_df) && !is.na(spline_knots)) { stop("Specify either `spline_df` or `spline_knots`, but not both.") } if (!is.na(spline_knots) && length(spline_knots)<3) { stop("`spline_knots` must be a numeric vector of at least length 3.") } # Create spline basis if (!is.na(spline_df)) { spl_bnd_knots <- as.numeric(stats::quantile(dat_v$s, c(0.05,0.95), na.rm=T)) spl_knots <- seq(spl_bnd_knots[1], spl_bnd_knots[2], length.out=spline_df+1)[c(2:spline_df)] } else { spl_bnd_knots <- spline_knots[c(1,length(spline_knots))] spl_knots <- spline_knots[c(2:(length(spline_knots)-1))] } spl_basis <- splines::ns( x = dat_v$s, knots = spl_knots, intercept = F, Boundary.knots = spl_bnd_knots ) for (i in c(1:(dim(spl_basis)[2]))) { dat_v_spl[[paste0("s",i)]] <- spl_basis[,i] } dim_s <- dim(spl_basis)[2] if (edge_ind) { dim_s <- dim_s + 1 min_s <- min(dat_v$s, na.rm=T) dat_v_spl[[paste0("s",dim_s)]] <- In(dat_v$s==min_s) # !!!!! Should this be dim_s+1 ????? s_to_spl <- function(s) { spl <- as.numeric(splines::ns( x = s, knots = spl_knots, intercept = F, Boundary.knots = spl_bnd_knots )) return(c(spl, In(s==min_s))) } } else { s_to_spl <- function(s) { as.numeric(splines::ns( x = s, knots = spl_knots, intercept = F, Boundary.knots = spl_bnd_knots )) } } } else { if (edge_ind) { dim_s <- 2 min_s <- min(dat_v$s, na.rm=T) dat_v_spl[[paste0("s",dim_s)]] <- In(dat_v$s==min_s) s_to_spl <- function(s) { c(s, In(s==min_s)) } } else { dim_s <- 1 s_to_spl <- function(s) { s } basic_cox_model <- T } } # Create phase-two data objects (unrounded) dat_v2 <- dat_v[dat_v$z==1,] dat_v2_spl <- dat_v_spl[dat_v$z==1,, drop=F] # Alias random variables WT <- dat_v2$weights ST <- dat_v2$strata n_vacc <- attr(dat, "n_vacc") dim_x <- attr(dat_v, "dim_x") X <- dat_v2[,c(1:dim_x), drop=F] class(X) <- "data.frame" SP <- dat_v2_spl V_ <- t(as.matrix(cbind(X,SP))) Y_ <- dat_v2$y D_ <- dat_v2$delta dim_v <- dim(V_)[1] # Create set of event times i_ev <- which(D_==1) # Fit an IPS-weighted Cox model model <- survival::coxph( formula = stats::formula(paste0("survival::Surv(y,delta)~", paste(names(X),collapse="+"), "+", paste(names(SP),collapse="+"))), data = cbind(y=Y_, delta=D_, X, SP), weights = WT ) coeffs <- model$coefficients beta_n <- as.numeric(coeffs) if (return_p_value) { if (basic_cox_model) { test_res <- list(p=summary(model)$coefficients["s1","Pr(>|z|)"]) } else { p_msg <- paste0("Cox-based P-values are only available for the basic Cox", " model (i.e., not for the spline model or the edge indi", "cator model).") test_res <- list(p=p_msg) } if (p_val_only) { return(test_res) } } if (any(is.na(coeffs))) { if (any(is.na(coeffs[which(substr(names(coeffs),1,1)=="x")]))) { na_coeffs <- names(coeffs)[which(is.na(coeffs))] stop(paste0("The following covariate coefficients were NA.: ", paste(na_coeffs, collapse=","), " Try removing these coefficients and rerunning.")) # !!!!! Automatically omit from the model, as is done for spline coeffs } if (any(is.na(coeffs[which(substr(names(coeffs),1,1)=="s")]))) { warning(paste0("Some spline coefficients were NA; these coefficients hav", "e been automatically omitted from the model")) na_inds <- as.numeric(which(is.na(coeffs))) s_na_inds <- which(is.na(coeffs[which(substr(names(coeffs),1,1)=="s")])) s_na_inds <- as.numeric(s_na_inds) beta_n <- beta_n[-na_inds] SP <- SP[,-s_na_inds] names(SP) <- paste0("s", c(1:length(SP))) V_ <- t(as.matrix(cbind(X,SP))) dim_v <- dim(V_)[1] s_to_spl2 <- s_to_spl s_to_spl <- function(s) { s_to_spl2(s)[-s_na_inds] } } } LIN <- as.numeric(t(beta_n)%*%V_) # Intermediate functions { S_0n <- (function() { .cache <- new.env() function(x) { val <- .cache[[as.character(x)]] if (is.null(val)) { val <- (function(x) { (1/n_vacc) * sum(WT*In(Y_>=x)*exp(LIN)) })(x) .cache[[as.character(x)]] <- val } return(val) } })() S_1n <- (function() { .cache <- new.env() function(x) { val <- .cache[[as.character(x)]] if (is.null(val)) { val <- (function(x) { (1/n_vacc) * as.numeric(V_ %*% (WT*In(Y_>=x)*exp(LIN))) })(x) .cache[[as.character(x)]] <- val } return(val) } })() S_2n <- (function() { .cache <- new.env() function(x) { val <- .cache[[as.character(x)]] if (is.null(val)) { val <- (function(x) { res <- matrix(NA, nrow=dim_v, ncol=dim_v) for (i in c(1:dim_v)) { for (j in c(1:dim_v)) { if (!is.na(res[j,i])) { res[i,j] <- res[j,i] } else { res[i,j] <- (1/n_vacc)*sum(WT*In(Y_>=x)*V_[i,]*V_[j,]*exp(LIN)) } } } return(res) })(x) .cache[[as.character(x)]] <- val } return(val) } })() m_n <- function(x) { S_1n(x) / S_0n(x) } } # Estimated information matrix (for an individual) I_tilde <- Reduce("+", lapply(i_ev, function(i) { WT[i] * ( (S_2n(Y_[i])/S_0n(Y_[i])) - m_n(Y_[i]) %*% t(m_n(Y_[i])) ) })) I_tilde <- (1/n_vacc)*I_tilde I_tilde_inv <- solve(I_tilde) # Score function (Cox model) l_n <- function(v_i,d_i,y_i) { d_i*(v_i-m_n(y_i)) - (1/n_vacc)*Reduce("+", lapply(i_ev, function(j) { (WT[j]*exp(sum(v_i*beta_n))*In(Y_[j]<=y_i) * (v_i-m_n(Y_[j]))) / S_0n(Y_[j]) })) } # Influence function: beta_hat (regular Cox model) l_tilde <- (function() { .cache <- new.env() function(v_i,d_i,y_i) { key <- paste(c(v_i,d_i,y_i), collapse=" ") val <- .cache[[key]] if (is.null(val)) { val <- (function(v_i,d_i,y_i) { I_tilde_inv %*% l_n(v_i,d_i,y_i) })(v_i,d_i,y_i) .cache[[key]] <- val } return(val) } })() # Create p_n and p1_n vectors n_strata <- max(dat_v$strata) p_n <- c() p1_n <- c() for (c in c(1:n_strata)) { p_n[c] <- mean(c==dat_v$strata) p1_n[c] <- mean(c==dat_v$strata & dat_v$z==1) } # Influence function: beta_hat (est. weights) infl_fn_beta <- (function() { .cache <- new.env() exp_terms <- list() for (i in c(1:max(dat_v$strata))) { js <- which(ST==i) if (length(js)>0) { exp_terms[[i]] <- (1/length(js)) * Reduce("+", lapply(js, function(j) { l_tilde(V_[,j],D_[j],Y_[j]) })) } else { exp_terms[[i]] <- as.matrix(rep(0,dim_v)) # Avoid NAs in small samples } } function(v_i,z_i,d_i,y_i,wt_i,st_i) { key <- paste(c(v_i,z_i,d_i,y_i,wt_i,st_i), collapse=" ") val <- .cache[[key]] if (is.null(val)) { val <- (function(v_i,z_i,d_i,y_i,wt_i,st_i) { if (z_i) { piece_1 <- wt_i*l_tilde(v_i,d_i,y_i) } else { piece_1 <- as.matrix(rep(0,dim_v)) } if (p1_n[st_i]!=0) { piece_2 <- (1 - (z_i*p_n[st_i])/p1_n[st_i]) * exp_terms[[st_i]] } else { piece_2 <- as.matrix(rep(0,dim_v)) # Avoid NAs in small samples } return(as.numeric(piece_1+piece_2)) })(v_i,z_i,d_i,y_i,wt_i,st_i) .cache[[key]] <- val } return(val) } })() # Nuisance constant: mu_n mu_n <- -1 * (1/n_vacc) * as.numeric(Reduce("+", lapply(i_ev, function(j) { (WT[j] * In(Y_[j]<=t_0) * m_n(Y_[j])) / S_0n(Y_[j]) }))) # Nuisance function: v_1n v_1n <- (function() { .cache <- new.env() function(st_i,z_i,y_j) { key <- paste(c(st_i,z_i,y_j), collapse=" ") val <- .cache[[key]] if (is.null(val)) { val <- (function(st_i,z_i,y_j) { k_set <- which(ST==st_i) if (length(k_set)>0) { return( (1/n_vacc) * (p1_n[st_i]-p_n[st_i]*z_i)/(p1_n[st_i])^2 * sum( unlist(lapply(k_set, function(k) { In(Y_[k]>=y_j) * exp(sum(beta_n*V_[,k])) })) ) ) } else { return(0) } })(st_i,z_i,y_j) .cache[[key]] <- val } return(val) } })() # Nuisance function: v_2n v_2n <- (function() { .cache <- new.env() function(st_i,z_i) { key <- paste(c(st_i,z_i), collapse=" ") val <- .cache[[key]] if (is.null(val)) { val <- (function(st_i,z_i) { k_set <- which(ST==st_i) if (length(k_set)>0) { return( (1/n_vacc) * (p1_n[st_i]-p_n[st_i]*z_i)/(p1_n[st_i])^2 * sum( unlist(lapply(k_set, function(k) { ( D_[k] * In(Y_[k]<=t_0) ) / S_0n(Y_[k]) })) ) ) } else { return(0) } })(st_i,z_i) .cache[[key]] <- val } return(val) } })() # Breslow estimator Lambda_n <- function(t) { (1/n_vacc) * sum(unlist(lapply(i_ev, function(i) { WT[i] * ( In(Y_[i]<=t) / S_0n(Y_[i]) ) }))) } # Lambda_n_alt <- survival::basehaz(model, centered=FALSE) # !!!!! Debugging # browser() # !!!!! Debugging # Survival estimator (at a point) Q_n <- (function() { Lambda_n_t_0 <- Lambda_n(t_0) function(z) { exp(-exp(sum(z*beta_n))*Lambda_n_t_0) } })() # Influence function: Breslow estimator (est. weights) infl_fn_Lambda <- (function() { .cache <- new.env() function(v_i,z_i,d_i,y_i,wt_i,st_i) { key <- paste(c(v_i,z_i,d_i,y_i,wt_i,st_i), collapse=" ") val <- .cache[[key]] if (is.null(val)) { val <- (function(v_i,z_i,d_i,y_i,wt_i,st_i) { pc_4 <- (1/n_vacc) * sum(unlist(lapply(i_ev, function(j) { ( WT[j] * In(Y_[j]<=t_0) * v_1n(st_i,z_i,Y_[j]) ) / (S_0n(Y_[j]))^2 }))) pc_5 <- sum(mu_n*infl_fn_beta(v_i,z_i,d_i,y_i,wt_i,st_i)) pc_2 <- v_2n(st_i,z_i) if (z_i==1) { pc_1 <- ( wt_i * d_i * In(y_i<=t_0) ) / S_0n(y_i) pc_3 <- (1/n_vacc) * sum(unlist(lapply(i_ev, function(j) { (WT[j]*In(Y_[j]<=t_0)*wt_i*In(y_i>=Y_[j])*exp(sum(beta_n*v_i))) / (S_0n(Y_[j]))^2 }))) return(pc_1+pc_2+pc_5-pc_3-pc_4) } else { return(pc_2+pc_5-pc_4) } })(v_i,z_i,d_i,y_i,wt_i,st_i) .cache[[key]] <- val } return(val) } })() # Compute marginalized risk res_cox <- list() Lambda_n_t_0 <- Lambda_n(t_0) if (attr(dat, "covariates_ph2")) { res_cox$est_marg <- unlist(lapply(s_out, function(s) { (1/n_vacc) * sum(dat_v2$weights * apply(dat_v2, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) s_spl <- s_to_spl(s) exp(-1*exp(sum(beta_n*c(x_i,s_spl)))*Lambda_n_t_0) })) })) } else { res_cox$est_marg <- unlist(lapply(s_out, function(s) { (1/n_vacc) * sum(apply(dat_v, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) s_spl <- s_to_spl(s) exp(-1*exp(sum(beta_n*c(x_i,s_spl)))*Lambda_n_t_0) })) })) } # Compute variance estimate if (ci_type!="none") { res_cox$var_est_marg <- unlist(lapply(s_out, function(s) { # res_cox$var_est_marg <- unlist(lapply(s_out[length(s_out)], function(s) { # !!!!! Debugging # Precalculate pieces dependent on s s_spl <- s_to_spl(s) if (attr(dat, "covariates_ph2")) { K_n <- (1/n_vacc) * Reduce("+", apply2(dat_v2, 1, function(r) { wts <- r[["weights"]] x_i <- as.numeric(r[1:dim_x]) Q <- Q_n(c(x_i,s_spl)) explin <- exp(sum(c(x_i,s_spl)*beta_n)) K_n1 <- wts * Q K_n2 <- wts * Q * explin K_n3 <- wts * Q * explin * c(x_i,s_spl) return(c(K_n1,K_n2,K_n3)) }, simplify=F)) K_n1 <- K_n[1] K_n2 <- K_n[2] K_n3 <- K_n[3:length(K_n)] K_n4 <- (function() { .cache <- new.env() function(st_i,s) { key <- paste(c(st_i,s), collapse=" ") val <- .cache[[key]] if (is.null(val)) { val <- (function(st_i,s) { k_set <- which(ST==st_i) if (length(k_set)>0) { return(sum(unlist(lapply(k_set, function(k) { Q_n(c(as.numeric(X[k,]),s_spl)) })))) } else { return(0) } })(st_i,s) .cache[[key]] <- val } return(val) } })() } else { K_n <- (1/n_vacc) * Reduce("+", apply2(dat_v, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) Q <- Q_n(c(x_i,s_spl)) explin <- exp(sum(c(x_i,s_spl)*beta_n)) K_n1 <- Q K_n2 <- Q * explin K_n3 <- Q * explin * c(x_i,s_spl) return(c(K_n1,K_n2,K_n3)) }, simplify=F)) K_n1 <- K_n[1] K_n2 <- K_n[2] K_n3 <- K_n[3:length(K_n)] } # !!!!! if (F) { vec1 <- (1/n_vacc^2) * sum((apply(dat_v, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) if (!is.na(r[["s"]])) { s_i <- s_to_spl(r[["s"]]) } else { s_i <- NA } z_i <- r[["z"]] d_i <- r[["delta"]] y_i <- r[["y"]] wt_i <- r[["weights"]] st_i <- r[["strata"]] pc_2 <- Lambda_n_t_0 * sum( K_n3 * infl_fn_beta(c(x_i,s_i),z_i,d_i,y_i,wt_i,st_i) ) pc_3 <- K_n2 * infl_fn_Lambda(c(x_i,s_i),z_i,d_i,y_i,wt_i,st_i) pc_4 <- K_n1 # if (ii==77) { browser() } # !!!!! # ii <<- ii+1 # !!!!! if (attr(dat, "covariates_ph2")) { den <- sum(ST==st_i) k_n_i <- ifelse(den!=0, (1-wt_i)/den, 0) # !!!!! this line might be problematic pc_5 <- k_n_i * K_n4(st_i,s) return((pc_2+pc_3+pc_4-pc_1-pc_5)^2) } else { pc_1 <- Q_n(c(x_i,s_spl)) return((pc_2+pc_3+pc_4-pc_1)^2) } }))) var1 <- (1/n_vacc^2) * sum(vec1) vec2 <- (1/n_vacc^2) * sum((apply(dat_v, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) if (!is.na(r[["s"]])) { s_i <- s_to_spl(r[["s"]]) } else { s_i <- NA } z_i <- r[["z"]] d_i <- r[["delta"]] y_i <- r[["y"]] wt_i <- r[["weights"]] st_i <- r[["strata"]] pc_2 <- Lambda_n_t_0 * sum( K_n3 * infl_fn_beta(c(x_i,s_i),z_i,d_i,y_i,wt_i,st_i) ) pc_3 <- K_n2 * infl_fn_Lambda(c(x_i,s_i),z_i,d_i,y_i,wt_i,st_i) pc_4 <- K_n1 # if (ii==77) { browser() } # !!!!! # ii <<- ii+1 # !!!!! if (attr(dat, "covariates_ph2")) { pc_1 <- wt_i * Q_n(c(x_i,s_spl)) den <- sum(ST==st_i) k_n_i <- ifelse(den!=0, (1-wt_i)/den, 0) # !!!!! this line might be problematic pc_5 <- k_n_i * K_n4(st_i,s) return((pc_2+pc_3+pc_4-pc_1-pc_5)^2) } else { pc_1 <- Q_n(c(x_i,s_spl)) return((pc_2+pc_3+pc_4-pc_1)^2) } }))) var2 <- (1/n_vacc^2) * sum(vec2) browser() } # ii <- 1 # !!!!! return((1/n_vacc^2) * sum((apply(dat_v, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) # This will include NAs if is.na(r[["s"]]) and covariates_ph2=T; make sure this doesn't cause issues if (!is.na(r[["s"]])) { s_i <- s_to_spl(r[["s"]]) } else { s_i <- NA } z_i <- r[["z"]] d_i <- r[["delta"]] y_i <- r[["y"]] wt_i <- r[["weights"]] st_i <- r[["strata"]] pc_2 <- Lambda_n_t_0 * sum( K_n3 * infl_fn_beta(c(x_i,s_i),z_i,d_i,y_i,wt_i,st_i) ) pc_3 <- K_n2 * infl_fn_Lambda(c(x_i,s_i),z_i,d_i,y_i,wt_i,st_i) pc_4 <- K_n1 # if (ii==77) { browser() } # !!!!! # ii <<- ii+1 # !!!!! if (attr(dat, "covariates_ph2")) { if (wt_i==0) { pc_1 <- 0 } else { pc_1 <- wt_i * Q_n(c(x_i,s_spl)) } den <- sum(ST==st_i) k_n_i <- ifelse(den!=0, (1-wt_i)/den, 0) # !!!!! this line might be problematic pc_5 <- k_n_i * K_n4(st_i,s) return((pc_2+pc_3+pc_4-pc_1-pc_5)^2) } else { pc_1 <- Q_n(c(x_i,s_spl)) return((pc_2+pc_3+pc_4-pc_1)^2) } })))) })) } # Extract estimates and SEs ests_cr <- 1-res_cox$est_marg # Generate confidence limits if (ci_type=="none") { ci_lo_cr <- ci_up_cr <- ses_cr <- rep(NA, length(ests_cr)) } else { ses_cr <- sqrt(res_cox$var_est_marg) if (ci_type=="regular") { ci_lo_cr <- ests_cr - 1.96*ses_cr ci_up_cr <- ests_cr + 1.96*ses_cr } else if (ci_type=="truncated") { ci_lo_cr <- pmin(pmax(ests_cr - 1.96*ses_cr, 0), 1) ci_up_cr <- pmin(pmax(ests_cr + 1.96*ses_cr, 0), 1) } else if (ci_type=="transformed") { ci_lo_cr <- expit(logit(ests_cr) - 1.96*deriv_logit(ests_cr)*ses_cr) ci_up_cr <- expit(logit(ests_cr) + 1.96*deriv_logit(ests_cr)*ses_cr) } else if (ci_type=="transformed 2") { ci_lo_cr <- expit2(logit2(ests_cr) - 1.96*deriv_logit2(ests_cr)*ses_cr) ci_up_cr <- expit2(logit2(ests_cr) + 1.96*deriv_logit2(ests_cr)*ses_cr) } } # Create results object res <- list() if (cr) { res$cr <- list(s=s_out, est=ests_cr, se=ses_cr, ci_lower=ci_lo_cr, ci_upper=ci_up_cr) } # Compute CVE if (cve) { res$cve <- list(s=s_out) if (attr(dat, "groups")!="both") { stop("Placebo group not detected.") } ov <- est_overall(dat=dat, t_0=t_0, method=placebo_risk_method, ve=F) risk_p <- ov[ov$group=="placebo","est"] se_p <- ov[ov$group=="placebo","se"] # This equals sd_p/n_orig res$cve$est <- 1 - res$cr$est/risk_p if (ci_type=="none") { na_vec <- rep(NA, length(res$cve$s_out)) res$cve$se <- na_vec res$cve$ci_lower <- na_vec res$cve$ci_upper <- na_vec } else { res$cve$se <- sqrt(ses_cr^2/risk_p^2 + (res$cr$est^2*se_p^2)/risk_p^4) if (ci_type=="regular") { res$cve$ci_lower <- res$cve$est - 1.96*res$cve$se res$cve$ci_upper <- res$cve$est + 1.96*res$cve$se } else if (ci_type=="truncated") { res$cve$ci_lower <- pmin(res$cve$est - 1.96*res$cve$se, 1) res$cve$ci_upper <- pmin(res$cve$est + 1.96*res$cve$se, 1) } else if (ci_type=="transformed") { res$cve$ci_lower <- 1 - exp( log(1-res$cve$est) + 1.96*(1/(1-res$cve$est))*res$cve$se ) res$cve$ci_upper <- 1 - exp( log(1-res$cve$est) - 1.96*(1/(1-res$cve$est))*res$cve$se ) } else if (ci_type=="transformed 2") { res$cve$ci_lower <- 1 - exp2( log2(1-res$cve$est) + 1.96*deriv_log2(1-res$cve$est)*res$cve$se ) res$cve$ci_upper <- 1 - exp2( log2(1-res$cve$est) - 1.96*deriv_log2(1-res$cve$est)*res$cve$se ) } # # !!!!! OLD !!!!! # res$cve$se <- NA # res$cve$ci_lower <- 1 - res$cr$ci_up/risk_p # !!!!! Add placebo group correction # res$cve$ci_upper <- 1 - res$cr$ci_lo/risk_p # !!!!! Add placebo group correction } } # Return P-value and/or extras if (return_p_value) { res$p <- test_res$p } if (return_extras) { res$extras <- list(model=model) } return(res) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/est_cox.R
#' Estimate mediation effects #' #' @description Estimate mediation effects, including the natural direct effect #' (NDE), the natural indirect effect (NIE), and the proportion mediated #' (PM). See references for definitions of these objects. #' @param dat A data object returned by load_data #' @param type One of c("NP", "Cox"). This specifies whether to estimate the #' effects using a marginalized Cox proportional hazards model or using a #' nonparametric estimator. #' @param t_0 Time point of interest #' @param nde Boolean. If TRUE, the natural direct effect is computed and #' returned. #' @param nie Boolean. If TRUE, the natural indirect effect is computed and #' returned. #' @param pm Boolean. If TRUE, the proportion mediated is computed and returned. #' @param scale One of c("RR", "VE"). This determines whether NDE and NIE #' estimates and CIs are computed on the risk ratio (RR) scale or the #' vaccine efficacy (VE) scale. The latter equals one minus the former. #' @param params_np A list of options returned by \code{\link{params_med_np}} #' that are relevant if type="NP". #' @return A dataframe containing the following columns: \itemize{ #' \item{\code{effect}: one of c("NDE", "NIE", "PM")} #' \item{\code{est}: point estimate} #' \item{\code{se}: standard error of point estimate} #' \item{\code{ci_lower}: a confidence interval lower limit} #' \item{\code{ci_upper}: a confidence interval upper limit} #' } #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_np <- est_med(dat=dat, type="NP", t_0=578) #' } #' @references Fay MP and Follmann DA (2023). Mediation Analyses for the Effect #' of Antibodies in Vaccination <doi:10.48550/arXiv.2208.06465> #' @export est_med <- function( dat, type="NP", t_0, nde=TRUE, nie=TRUE, pm=TRUE, scale="RR", # ci_type="transformed", return_extras=FALSE, # params_cox=params_med_cox(), params_np=params_med_np() ) { # !!!!! Need to refactor with est_ce functions if (!(scale %in% c("RR", "VE"))) { stop("`scale` must equal one of c('RR', 'VE').") } if (!methods::is(dat,"vaccine_dat")) { stop(paste0("`dat` must be an object of class 'vaccine_dat' returned by ", "load_data().")) } if (!(attr(dat, "groups") %in% c("vaccine", "both"))) { stop("Vaccine group data not detected.") } if ((nde||pm) && !(attr(dat, "groups") %in% c("placebo", "both"))) { stop("Placebo group data not detected.") } if (!(nde||nie||pm)) { stop("At least one of `nde`, `nie`, or `pm` must be TRUE.") } if (type=="Cox") { stop("Coming soon!") } if (type=="NP") { # Set params .default_params <- params_med_np() for (i in c(1:length(.default_params))) { p_name <- names(.default_params)[i] if (is.null(params_np[[p_name]])) { params_np[[p_name]] <- .default_params[[i]] } } p <- params_np # Create filtered data objects dat_v <- dat[dat$a==1,] dat_p <- dat[dat$a==0,] # Alias variables dim_x <- attr(dat, "dim_x") n_vacc <- attr(dat, "n_vacc") n_plac <- attr(dat, "n_plac") n <- attr(dat, "n") p_vacc <- n_vacc/n p_plac <- n_plac/n # Rescale S to lie in [0,1] and create grid for rounding s_min <- min(dat_v$s, na.rm=T) s_max <- max(dat_v$s, na.rm=T) s_shift <- -1 * s_min s_scale <- 1/(s_max-s_min) dat_v$s <- (dat_v$s+s_shift)*s_scale dat$s <- ifelse(dat$a==1, (dat$s+s_shift)*s_scale, 0) grid <- create_grid(dat_v, p$grid_size, t_0) # !!!!! feed in dat instead (1) # Create rounded filtered data objects dat_v_rd <- round_dat(dat_v, grid, p$grid_size) # !!!!! see (1) above dat_p_rd <- round_dat(dat_p, grid, p$grid_size) # !!!!! see (1) above datx_v_rd <- dat_v_rd[, c(1:dim_x), drop=F] datx_p_rd <- dat_p_rd[, c(1:dim_x), drop=F] class(datx_v_rd) <- "data.frame" class(datx_p_rd) <- "data.frame" dat_v2_rd <- dat_v_rd[dat_v_rd$z==1,] dat_rd <- round_dat(dat, grid, p$grid_size) # !!!!! see (1) above # Precomputation values for conditional survival/censoring estimators x_distinct <- dplyr::distinct(datx_v_rd) x_distinct <- cbind("x_index"=c(1:nrow(x_distinct)), x_distinct) vals_pre <- expand.grid(t=grid$y, x_index=x_distinct$x_index, s=grid$s) vals_pre <- dplyr::inner_join(vals_pre, x_distinct, by="x_index") vals <- list( t = vals_pre$t, x = subset(vals_pre, select=names(datx_v_rd)), s = vals_pre$s ) # Fit conditional survival estimator (vaccine group) srvSL <- construct_Q_n(p$surv_type, dat_v2_rd, vals) Q_n <- srvSL$srv Qc_n <- srvSL$cens # Compute various nuisance functions omega_n <- construct_omega_n(Q_n, Qc_n, t_0, grid) f_sIx_n <- construct_f_sIx_n(dat_v2_rd, type=p$density_type, k=p$density_bins, z1=F) f_s_n <- construct_f_s_n(dat_v_rd, f_sIx_n) g_n <- construct_g_n(f_sIx_n, f_s_n) f_n_srv <- construct_f_n_srv(Q_n, Qc_n, grid) # Compute edge-corrected estimator and standard error p_n <- (1/n_vacc) * sum(dat_v2_rd$weights * In(dat_v2_rd$s!=0)) g_sn <- construct_g_sn(dat_v2_rd, f_n_srv, g_n, p_n) r_Mn_edge_est <- r_Mn_edge(dat_v_rd, g_sn, g_n, p_n, Q_n, omega_n, t_0) r_Mn_edge_est <- min(max(r_Mn_edge_est, 0), 1) infl_fn_r_Mn_edge <- construct_infl_fn_r_Mn_edge(Q_n, g_sn, omega_n, g_n, r_Mn_edge_est, p_n, t_0) # Create results object res <- data.frame( "effect" = character(), "est" = double(), "se" = double(), "ci_lower" = double(), "ci_upper" = double() ) # Create edge influence function (relative to the whole dataset) infl_fn_edge_2 <- function(a,z,weights,s,x,y,delta) { if (a==0) { return(0) } else { return((1/p_vacc)*infl_fn_r_Mn_edge(z,weights,s,x,y,delta)) } } # Calculate NDE if (nde) { # Precomputation values for conditional survival/censoring estimators x_distinct_p <- dplyr::distinct(datx_p_rd) x_distinct_p <- cbind("x_index"=c(1:nrow(x_distinct_p)), x_distinct_p) vals_p_pre <- expand.grid(t=grid$y, x_index=x_distinct_p$x_index) vals_p_pre <- dplyr::inner_join(vals_p_pre, x_distinct_p, by="x_index") vals_p <- list( t = vals_p_pre$t, x = subset(vals_p_pre, select=names(datx_p_rd)) ) # Fit conditional survival estimator (placebo group) srvSL_p <- construct_Q_noS_n(type=p$surv_type, dat_p_rd, vals_p) Q_noS_n <- srvSL_p$srv Qc_noS_n <- srvSL_p$cens # Construct other nuisance estimators omega_noS_n <- construct_omega_noS_n(Q_noS_n, Qc_noS_n, t_0, grid) risk_p_est <- risk_overall_np_p(dat_p_rd, Q_noS_n, omega_noS_n, t_0) infl_fn_risk_p <- construct_infl_fn_risk_p(dat_p_rd, Q_noS_n, omega_noS_n, t_0, p_plac) # !!!!! NEW CODE if (T) { # Precomputation values for conditional survival/censoring estimators x_distinct_v <- dplyr::distinct(datx_v_rd) x_distinct_v <- cbind("x_index"=c(1:nrow(x_distinct_v)), x_distinct_v) vals_v_pre <- expand.grid(t=grid$y, x_index=x_distinct_v$x_index) vals_v_pre <- dplyr::inner_join(vals_v_pre, x_distinct_v, by="x_index") vals_v <- list( t = vals_v_pre$t, x = subset(vals_v_pre, select=names(datx_v_rd)) ) # Fit conditional survival estimator (placebo group) srvSL_v <- construct_Q_noS_n(type=p$surv_type, dat_v_rd, vals_v) Q_noS_n_v <- srvSL_v$srv Qc_noS_n_v <- srvSL_v$cens # Construct other nuisance estimators omega_noS_n_v <- construct_omega_noS_n(Q_noS_n_v, Qc_noS_n_v, t_0, grid) risk_v_est <- risk_overall_np_v_v2(dat_v_rd, Q_noS_n_v, omega_noS_n_v, t_0) # print("!!!!! DEBUGGING !!!!!") # print(paste("risk_v_est:", risk_v_est)) # print(paste("risk_p_est:", risk_p_est)) infl_fn_risk_v <- construct_infl_fn_risk_v_v2(dat_v_rd, Q_noS_n_v, # !!!!! Should still work omega_noS_n_v, t_0, p_vacc) # !!!!! Should still work } # q_tilde_n <- memoise2(function(x,y,delta) { # # !!!!! Replace with sapply # num <- sum(apply(dat_v2_rd, 1, function(r) { # r[["weights"]] * (omega_n(x,r[["s"]],y,delta)-Q_n(t_0,x,r[["s"]])) * # f_n_srv(y, delta, x, r[["s"]]) * g_n(r[["s"]],x) # })) # den <- sum(apply(dat_v2_rd, 1, function(r) { # r[["weights"]] * f_n_srv(y, delta, x, r[["s"]]) * g_n(r[["s"]],x) # })) # if (den==0) { # return(0) # } else { # return(num/den) # } # }) # risk_v_est <- risk_overall_np_v(dat_v_rd, g_n, Q_n, omega_n, f_n_srv, # q_tilde_n, t_0) # infl_fn_risk_v <- construct_infl_fn_risk_v(dat_v_rd, Q_n, g_n, omega_n, # q_tilde_n, t_0, p_vacc) nde_est <- r_Mn_edge_est/risk_p_est sigma2_nde_est <- mean(apply(dat_rd, 1, function(r) { x <- as.numeric(r[1:dim_x]) if_p <- infl_fn_risk_p(r[["a"]], r[["delta"]], r[["y"]], x) if_edge <- infl_fn_edge_2(r[["a"]], r[["z"]], r[["weights"]], r[["s"]], x, r[["y"]], r[["delta"]]) return(((1/risk_p_est)*if_edge-(r_Mn_edge_est/risk_p_est^2)*if_p)^2) }), na.rm=T) # !!!!! Test getting rid of na.rm=T nde_se <- sqrt(sigma2_nde_est/n) nde_lo <- exp(log(nde_est)-1.96*(1/nde_est)*nde_se) nde_up <- exp(log(nde_est)+1.96*(1/nde_est)*nde_se) res[nrow(res)+1,] <- list("NDE", nde_est, nde_se, nde_lo, nde_up) } # Calculate NIE if (nie) { nie_est <- risk_v_est/r_Mn_edge_est sigma2_nie_est <- mean(apply(dat_rd, 1, function(r) { x <- as.numeric(r[1:dim_x]) # if_v <- infl_fn_risk_v(a=r[["a"]], z=r[["z"]], weight=r[["weights"]], # s=r[["s"]], x=x, y=r[["y"]], # delta=r[["delta"]]) if_v <- infl_fn_risk_v(r[["a"]], r[["delta"]], r[["y"]], x) if_edge <- infl_fn_edge_2(r[["a"]], r[["z"]], r[["weights"]], r[["s"]], x, r[["y"]], r[["delta"]]) return(((1/r_Mn_edge_est)*if_v-(risk_v_est/r_Mn_edge_est^2)*if_edge)^2) }), na.rm=T) # !!!!! Test getting rid of na.rm=T nie_se <- sqrt(sigma2_nie_est/n) nie_lo <- exp(log(nie_est)-1.96*(1/nie_est)*nie_se) nie_up <- exp(log(nie_est)+1.96*(1/nie_est)*nie_se) res[nrow(res)+1,] <- list("NIE", nie_est, nie_se, nie_lo, nie_up) } # Calculate PM if (pm) { pm_est <- 1 - (log(r_Mn_edge_est/risk_p_est) / log(risk_v_est/risk_p_est)) sigma2_pm_est <- mean(apply(dat_rd, 1, function(r) { rr <- risk_v_est/risk_p_est c_1 <- log(r_Mn_edge_est/risk_p_est) / risk_v_est c_2 <- log(risk_v_est/r_Mn_edge_est) / risk_p_est c_3 <- (-1*log(rr)) / r_Mn_edge_est x <- as.numeric(r[1:dim_x]) # if_v <- infl_fn_risk_v(a=r[["a"]], z=r[["z"]], weight=r[["weights"]], # s=r[["s"]], x=x, y=r[["y"]], # delta=r[["delta"]]) if_v <- infl_fn_risk_v(r[["a"]], r[["delta"]], r[["y"]], x) if_p <- infl_fn_risk_p(r[["a"]], r[["delta"]], r[["y"]], x) if_edge <- infl_fn_edge_2(a=r[["a"]], r[["z"]], r[["weights"]], r[["s"]], x, r[["y"]], r[["delta"]]) return((1/(log(rr))^2*(c_1*if_v+c_2*if_p+c_3*if_edge))^2) }), na.rm=T) # !!!!! Test getting rid of na.rm=T pm_se <- sqrt(sigma2_pm_est/n) pm_lo <- pm_est-1.96*pm_se pm_up <- pm_est+1.96*pm_se res[nrow(res)+1,] <- list("PM", pm_est, pm_se, pm_lo, pm_up) } if (scale=="VE") { # NDE res[res$effect=="NDE","est"] <- 1 - res[res$effect=="NDE","est"] res_lo_old <- res[res$effect=="NDE","ci_lower"] res_up_old <- res[res$effect=="NDE","ci_upper"] res[res$effect=="NDE","ci_lower"] <- 1 - res_up_old res[res$effect=="NDE","ci_upper"] <- 1 - res_lo_old # NIE res[res$effect=="NIE","est"] <- 1 - res[res$effect=="NIE","est"] res_lo_old <- res[res$effect=="NIE","ci_lower"] res_up_old <- res[res$effect=="NIE","ci_upper"] res[res$effect=="NIE","ci_lower"] <- 1 - res_up_old res[res$effect=="NIE","ci_upper"] <- 1 - res_lo_old } } return(res) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/est_med.R
#' Estimate CVE/CR nonparametrically #' #' @description See docs for est_ce and params_ce_cox #' @noRd est_np <- function( dat, t_0, cr, cve, s_out, ci_type, placebo_risk_method, return_p_value, return_extras, params, cf_folds, p_val_only=FALSE ) { # Set params .default_params <- params_ce_np() .default_params$gamma_type <- "Super Learner" # !!!!! Move to params or hard-code .default_params$q_n_type <- "zero" # !!!!! Temp; implement "standard" # .default_params$q_n_type <- "standard" # !!!!! Temp; implement "standard" .default_params$mono_cis <- T # !!!!! Move to params or hard-code for (i in c(1:length(.default_params))) { p_name <- names(.default_params)[i] if (is.null(params[[p_name]])) { params[[p_name]] <- .default_params[[i]] } } p <- params if (!(p$dir %in% c("decr", "incr"))) { stop("`dir` must equal one of c('decr','incr').") } else { dir_factor <- ifelse(p$dir=="decr", -1, 1) } # Create filtered data objects, alias variables dat_v <- dat[dat$a==1,] dim_x <- attr(dat, "dim_x") n_vacc <- attr(dat, "n_vacc") if (any(is.na(s_out))) { stop("NA values not allowed in s_out.") } # Rescale S to lie in [0,1] and create grid for rounding s_min <- min(dat_v$s, na.rm=T) s_max <- max(dat_v$s, na.rm=T) s_shift <- -1 * s_min s_scale <- 1/(s_max-s_min) dat_v$s <- (dat_v$s+s_shift)*s_scale grid <- create_grid(dat_v, p$grid_size, t_0) # !!!!! feed in dat instead ????? # Create additional filtered datasets dat_v_rd <- round_dat(dat_v, grid, p$grid_size) # !!!!! see (1) above; also, make grid_size a param, like in est_med dat_v2_rd <- dat_v_rd[dat_v_rd$z==1,] datx_v_rd <- dat_v_rd[, c(1:dim_x), drop=F] class(datx_v_rd) <- "data.frame" # Rescale/round s_out and remove s_out points outside [0,1] s_out_orig <- s_out s_out <- (s_out+s_shift)*s_scale na_head <- sum(s_out<0) na_tail <- sum(s_out>1) if (na_head>0) { s_out <- s_out[-c(1:na_head)] } len_p <- length(s_out) if (na_tail>0) { s_out <- s_out[-c((len_p-na_tail+1):len_p)] } s_out <- sapply(s_out, function(s) { grid$s[which.min(abs(grid$s-s))] }) # Precomputation values for conditional survival/censoring estimators if (attr(dat, "covariates_ph2")) { datx_v2_rd <- dat_v2_rd[, c(1:dim_x), drop=F] class(datx_v2_rd) <- "data.frame" x_distinct <- dplyr::distinct(datx_v2_rd) } else { x_distinct <- dplyr::distinct(datx_v_rd) } x_distinct <- cbind("x_index"=c(1:nrow(x_distinct)), x_distinct) vals_pre <- expand.grid(t=grid$y, x_index=x_distinct$x_index, s=grid$s) vals_pre <- dplyr::inner_join(vals_pre, x_distinct, by="x_index") vals <- list( t = vals_pre$t, x = subset(vals_pre, select=names(datx_v_rd)), s = vals_pre$s ) # Fit conditional survival estimator srvSL <- construct_Q_n(p$surv_type, dat_v2_rd, vals) Q_n <- srvSL$srv Qc_n <- srvSL$cens # Obtain minimum value (excluding edge point mass) if (p$edge_corr) { s_min2 <- min(dat_v_rd$s[dat_v_rd$s!=0], na.rm=T) } # Compute various nuisance functions omega_n <- construct_omega_n(Q_n, Qc_n, t_0, grid) f_sIx_n <- construct_f_sIx_n(dat_v2_rd, type=p$density_type, k=p$density_bins, z1=F) f_n_srv <- construct_f_n_srv(Q_n, Qc_n, grid) if (!p_val_only) { f_s_n <- construct_f_s_n(dat_v_rd, f_sIx_n) g_n <- construct_g_n(f_sIx_n, f_s_n) Phi_n <- construct_Phi_n(dat_v2_rd) r_tilde_Mn <- construct_r_tilde_Mn(dat_v_rd, Q_n, t_0) q_n <- construct_q_n(type=p$q_n_type, dat_v2_rd, omega_n, g_n, r_tilde_Mn, f_n_srv) Gamma_os_n <- construct_Gamma_os_n(dat_v_rd, omega_n, g_n, q_n, r_tilde_Mn) } if (return_p_value) { # Helper function to compute P values compute_p_val <- function(alt_type, beta_n, var_n) { if (alt_type=="incr") { p_val <- stats::pnorm(beta_n, mean=0, sd=sqrt(var_n), lower.tail=FALSE) } else if (alt_type=="decr") { p_val <- stats::pnorm(beta_n, mean=0, sd=sqrt(var_n)) } else if (alt_type=="two-tailed") { p_val <- stats::pchisq(beta_n^2/var_n, df=1, lower.tail=FALSE) } return(p_val) } # Construct additional nuisance functions etastar_n <- construct_etastar_n(Q_n, t_0, grid) q_tilde_n <- construct_q_tilde_n(type=p$q_n_type, f_n_srv, f_sIx_n, omega_n) Theta_os_n <- construct_Theta_os_n(dat_v_rd, omega_n, f_sIx_n, q_tilde_n, etastar_n) infl_fn_Theta <- construct_infl_fn_Theta(omega_n, f_sIx_n, q_tilde_n, etastar_n, Theta_os_n) infl_fn_beta_n <- construct_infl_fn_beta_n(infl_fn_Theta) # Functions needed for edge-corrected test # p_n <- (1/n_vacc) * sum(dat$weights * In(dat$s!=0)) # f_s_n <- construct_f_s_n(dat_orig, vlist$S_grid, f_sIx_n) # g_n <- construct_g_n(f_sIx_n, f_s_n) # g_sn <- construct_g_sn(dat, f_n_srv, g_n, p_n) # r_Mn_edge_est <- r_Mn_edge(dat_orig, dat, g_sn, g_n, p_n, Q_n, omega_n) # infl_fn_r_Mn_edge <- construct_infl_fn_r_Mn_edge(Q_n, g_sn, omega_n, g_n, # r_Mn_edge_est, p_n) # infl_fn_beta_en <- construct_infl_fn_beta_en(infl_fn_Theta, # infl_fn_r_Mn_edge) if (p$edge_corr) { stop("Edge-corrected test not yet implemented.") # # Construct pieces needed for beta_n # u_mc <- round(seq(0.001,1,0.001),3) # m <- length(u_mc) # lambda_1 <- mean(u_mc) # ~1/2 # lambda_2 <- mean((u_mc)^2) # ~1/3 # lambda_3 <- mean((u_mc)^3) # ~1/4 # beta_n <- mean(( # (lambda_1*lambda_2-lambda_3)*(u_mc-lambda_1) + # (lambda_2-lambda_1^2)*(u_mc^2-lambda_2) # ) * Theta_os_n(u_mc)) # infl_fn_beta_n <- construct_infl_fn_beta_n(infl_fn_Theta) # # # Construct pieces needed for beta_en # beta_en <- Theta_os_n(1) - r_Mn_edge_est # # # Calculate variance components # sigma2_bn <- 0 # sigma2_ben <- 0 # cov_n <- 0 # for (i in c(1:n_vacc)) { # z_i <- dat_orig$z[i] # s_i <- dat_orig$s[i] # x_i <- as.numeric(dat_orig$x[i,]) # y_i <- dat_orig$y[i] # delta_i <- dat_orig$delta[i] # weight_i <- dat_orig$weight[i] # # if_bn <- infl_fn_beta_n(s_i, y_i, delta_i, weight_i, x_i) # if_ben <- infl_fn_beta_en(z_i, x_i, y_i, delta_i, s_i, weight_i) # # sigma2_bn <- sigma2_bn + if_bn^2 # sigma2_ben <- sigma2_ben + if_ben^2 # cov_n <- cov_n + if_bn*if_ben # } # sigma_bn <- sqrt(sigma2_bn/n_vacc) # sigma_ben <- sqrt(sigma2_ben/n_vacc) # cov_n <- cov_n/n_vacc # rho_n <- cov_n/(sigma_bn*sigma_ben) # # # Calculate combined test statistic # beta_star_n <- sqrt(n_vacc/(2+2*rho_n)) * # (beta_n/sigma_bn + beta_en/sigma_ben) # # res[[length(res)+1]] <- list( # type = "combined 2", # p_val = compute_p_val(alt_type, beta_star_n, 1), # beta_n = beta_star_n, # var_n = 1 # ) } else { # Compute test statistic and variance estimate u_mc <- round(seq(0.01,1,0.01),2) m <- length(u_mc) lambda_1 <- mean(u_mc) # ~1/2 lambda_2 <- mean((u_mc)^2) # ~1/3 lambda_3 <- mean((u_mc)^3) # ~1/4 beta_n <- mean(( (lambda_1*lambda_2-lambda_3)*(u_mc-lambda_1) + (lambda_2-lambda_1^2)*(u_mc^2-lambda_2) ) * sapply(u_mc, Theta_os_n)) # !!!!! DEBUGGING if (F) { # browser() # !!!!! sd_n_0.2 <- sqrt((1/n_vacc^2) * sum(apply(dat_v_rd, 1, function(r) { infl_fn_Theta(u=0.2, x=as.numeric(r[1:dim_x]), y=r[["y"]], delta=r[["delta"]], s=r[["s"]], weight=r[["weights"]])^2 }))) sd_n_0.5 <- sqrt((1/n_vacc^2) * sum(apply(dat_v_rd, 1, function(r) { infl_fn_Theta(u=0.5, x=as.numeric(r[1:dim_x]), y=r[["y"]], delta=r[["delta"]], s=r[["s"]], weight=r[["weights"]])^2 }))) sd_n_0.8 <- sqrt((1/n_vacc^2) * sum(apply(dat_v_rd, 1, function(r) { infl_fn_Theta(u=0.8, x=as.numeric(r[1:dim_x]), y=r[["y"]], delta=r[["delta"]], s=r[["s"]], weight=r[["weights"]])^2 }))) res_temp <- list( Theta_n_0.2 = Theta_os_n(0.2), Theta_n_0.5 = Theta_os_n(0.5), Theta_n_0.8 = Theta_os_n(0.8), sd_n_0.2 = sd_n_0.2, sd_n_0.5 = sd_n_0.5, sd_n_0.8 = sd_n_0.8 ) return(res_temp) } var_n <- (1/n_vacc^2) * sum(apply(dat_v_rd, 1, function(r) { (infl_fn_beta_n(r[["s"]], r[["y"]], r[["delta"]], r[["weights"]], as.numeric(r[1:dim_x])))^2 })) test_res <- list( # p = compute_p_val(alt_type=p$dir, beta_n, var_n), p = compute_p_val(alt_type="two-tailed", beta_n, var_n), # !!!!! TEMP; two-tailed beta_n = beta_n, sd_n = sqrt(var_n) ) if (p_val_only) { return(list(p=test_res$p)) # return(test_res) # !!!!! } } if (F) { # res$extras <- list( # Theta_1.0 = Theta_os_n(1), # r_Mn_0.0 = r_Mn_edge_est, # # var_edge = var_edge, # # sd_edge = sqrt(var_edge), # beta_n = beta_n, # beta_en = beta_en, # sigma_bn = sigma_bn, # sigma_ben = sigma_ben, # rho_n = rho_n # ) # res$extras <- list( # Theta_0.1 = Theta_os_n(0.1), # Theta_0.4 = Theta_os_n(0.4), # Theta_0.8 = Theta_os_n(0.8), # etastar_0.1 = mean(sapply(c(1:n_vacc), function(i) { # etastar_n(u=0.1, x=as.numeric(dat_orig$x[i,])) # })), # etastar_0.4 = mean(sapply(c(1:n_vacc), function(i) { # etastar_n(u=0.4, x=as.numeric(dat_orig$x[i,])) # })), # etastar_0.8 = mean(sapply(c(1:n_vacc), function(i) { # etastar_n(u=0.8, x=as.numeric(dat_orig$x[i,])) # })) # ) } # DEBUG: return debugging components } # Compute edge-corrected estimator and standard error if (p$edge_corr) { if (attr(dat, "covariates_ph2")) { # stop("edge correction not yet available for covariates_ph2==T.") warning("edge correction not yet available for covariates_ph2==T.") # !!!!! } p_n <- (1/n_vacc) * sum(dat_v2_rd$weights * In(dat_v2_rd$s!=0)) g_sn <- construct_g_sn(dat_v2_rd, f_n_srv, g_n, p_n) r_Mn_edge_est <- r_Mn_edge(dat_v_rd, g_sn, g_n, p_n, Q_n, omega_n, t_0) r_Mn_edge_est <- min(max(r_Mn_edge_est, 0), 1) infl_fn_r_Mn_edge <- construct_infl_fn_r_Mn_edge(Q_n, g_sn, omega_n, g_n, r_Mn_edge_est, p_n, t_0) sigma2_edge_est <- mean(apply(dat_v_rd, 1, function(r) { (infl_fn_r_Mn_edge(r[["z"]], r[["weights"]], r[["s"]], as.numeric(r[1:dim_x]), r[["y"]], r[["delta"]]))^2 })) } # Compute GCM (or least squares line) and extract its derivative gcm_x_vals <- sapply(sort(unique(dat_v2_rd$s)), Phi_n) indices_to_keep <- !base::duplicated(gcm_x_vals) gcm_x_vals <- gcm_x_vals[indices_to_keep] gcm_y_vals <- dir_factor * sapply(sort(unique(dat_v2_rd$s))[indices_to_keep], Gamma_os_n) if (any(is.nan(gcm_y_vals)) || any(is.na(gcm_y_vals))) { stop("Gamma_os_n produced NAN or NA values.") } if (!any(gcm_x_vals==0)) { gcm_x_vals <- c(0, gcm_x_vals) gcm_y_vals <- c(0, gcm_y_vals) } if (p$convex_type=="GCM") { gcm <- fdrtool::gcmlcm(x=gcm_x_vals, y=gcm_y_vals, type="gcm") dGCM <- stats::approxfun( x = gcm$x.knots[-length(gcm$x.knots)], y = gcm$slope.knots, method = "constant", rule = 2, f = 0 ) } else if (p$convex_type=="CLS") { # This approach is experimental; asymptotic theory not yet developed gcm <- function(x) { 1 } # Ignored fit <- simest::cvx.lse.reg(t=gcm_x_vals, z=gcm_y_vals) pred_x <- round(seq(0,1,0.001),3) pred_y <- stats::predict(fit, newdata=pred_x) dGCM <- function(u) { width <- 0.05 u1 <- u - width/2; u2 <- u + width/2; if (u1<0) { u2 <- u2 - u1; u1 <- 0; } if (u2>1) { u1 <- u1 - u2 + 1; u2 <- 1; } u1 <- round(u1,3); u2 <- round(u2,3); ind1 <- which(pred_x==u1); ind2 <- which(pred_x==u2); y1 <- pred_y[ind1]; y2 <- pred_y[ind2]; return((y2-y1)/width) } } # Construct Grenander-based r_Mn estimator (and truncate to lie within [0,1]) r_Mn_Gr <- function(u) { min(max(dir_factor*dGCM(Phi_n(u)), 0), 1) } # Compute variance component nuisance estimators if (ci_type!="none") { f_sIx_z1_n <- construct_f_sIx_n(dat_v2_rd, type=p$density_type, k=p$density_bins, z1=T) f_s_z1_n <- construct_f_s_n(dat_v_rd, f_sIx_z1_n) gamma_n <- construct_gamma_n(dat_v_rd, type="Super Learner", omega_n, grid) g_zn <- construct_g_zn(dat_v_rd, type="Super Learner", f_sIx_n, f_sIx_z1_n) } # Create edge-corrected r_Mn estimator if (p$edge_corr) { r_Mn <- function(u) { if(u==0 || u<s_min2) { return(r_Mn_edge_est) } else { if (p$dir=="decr") { return(min(r_Mn_edge_est, r_Mn_Gr(u))) } else { return(max(r_Mn_edge_est, r_Mn_Gr(u))) } } } } else { r_Mn <- r_Mn_Gr } # Generate estimates for each point ests_cr <- sapply(s_out, r_Mn) # Generate confidence limits if (ci_type=="none") { ci_lo_cr <- rep(NA, length(ests_cr)) ci_up_cr <- rep(NA, length(ests_cr)) } else { # Construct variance scale factor function deriv_r_Mn <- construct_deriv_r_Mn(type=p$deriv_type, r_Mn, p$dir, grid) tau_n <- construct_tau_n(dat_v_rd, deriv_r_Mn, gamma_n, f_sIx_n, g_zn) # Generate variance scale factor for each point tau_ns <- sapply(s_out, tau_n) # Construct CIs # The 0.975 quantile of the Chernoff distribution occurs at roughly 1.00 qnt <- 1.00 if (ci_type=="regular") { ci_lo_cr <- ests_cr - (qnt*tau_ns)/(n_vacc^(1/3)) ci_up_cr <- ests_cr + (qnt*tau_ns)/(n_vacc^(1/3)) } else if (ci_type=="truncated") { ci_lo_cr <- pmax(ests_cr - (qnt*tau_ns)/(n_vacc^(1/3)), 0) ci_up_cr <- pmin(ests_cr + (qnt*tau_ns)/(n_vacc^(1/3)), 1) } else if (ci_type=="transformed") { ci_lo_cr <- expit( logit(ests_cr) - qnt*deriv_logit(ests_cr)*(tau_ns/(n_vacc^(1/3))) ) ci_up_cr <- expit( logit(ests_cr) + qnt*deriv_logit(ests_cr)*(tau_ns/(n_vacc^(1/3))) ) } else if (ci_type=="transformed 2") { ci_lo_cr <- expit2( logit2(ests_cr) - qnt*deriv_logit2(ests_cr)*(tau_ns/(n_vacc^(1/3))) ) ci_up_cr <- expit2( logit2(ests_cr) + qnt*deriv_logit2(ests_cr)*(tau_ns/(n_vacc^(1/3))) ) } # CI edge correction if (p$edge_corr) { se_edge_est <- sqrt(sigma2_edge_est/n_vacc) if (ci_type=="regular") { ci_lo_cr2 <- ests_cr[1] - 1.96*se_edge_est ci_up_cr2 <- ests_cr[1] + 1.96*se_edge_est } else if (ci_type=="truncated") { ci_lo_cr2 <- max(ests_cr[1] - 1.96*se_edge_est, 0) ci_up_cr2 <- min(ests_cr[1] - 1.96*se_edge_est, 1) } else if (ci_type=="transformed") { ci_lo_cr2 <- expit( logit(ests_cr[1]) - 1.96*deriv_logit(ests_cr[1])*se_edge_est ) ci_up_cr2 <- expit( logit(ests_cr[1]) + 1.96*deriv_logit(ests_cr[1])*se_edge_est ) } else if (ci_type=="transformed 2") { ci_lo_cr2 <- expit2( logit2(ests_cr[1]) - 1.96*deriv_logit2(ests_cr[1])*se_edge_est ) ci_up_cr2 <- expit2( logit2(ests_cr[1]) + 1.96*deriv_logit2(ests_cr[1])*se_edge_est ) } if (p$dir=="decr") { ind_edge <- In(r_Mn_edge_est<=ests_cr) ci_lo_cr <- ind_edge*pmin(ci_lo_cr,ci_lo_cr2) + (1-ind_edge)*ci_lo_cr ci_up_cr <- ind_edge*pmin(ci_up_cr,ci_up_cr2) + (1-ind_edge)*ci_up_cr ci_lo_cr[1] <- ci_lo_cr2 # !!!!! ci_up_cr[1] <- ci_up_cr2 # !!!!! } else { ind_edge <- In(r_Mn_edge_est>=ests_cr) ci_lo_cr <- ind_edge*pmax(ci_lo_cr,ci_lo_cr2) + (1-ind_edge)*ci_lo_cr ci_up_cr <- ind_edge*pmax(ci_up_cr,ci_up_cr2) + (1-ind_edge)*ci_up_cr ci_lo_cr[1] <- ci_lo_cr2 # !!!!! ci_up_cr[1] <- ci_up_cr2 # !!!!! } } # Monotone CI correction if (p$mono_cis) { new_lims <- monotonize_cis( ci_lo = ci_lo_cr, ci_up = ci_up_cr, dir = p$dir, type = "regular" ) ci_lo_cr <- new_lims$ci_lo ci_up_cr <- new_lims$ci_up } } # Create results object res <- list() if (cr) { res$cr <- list( s = s_out_orig, est = c(rep(NA,na_head), ests_cr, rep(NA,na_tail)), ci_lower = c(rep(NA,na_head), ci_lo_cr, rep(NA,na_tail)), ci_upper = c(rep(NA,na_head), ci_up_cr, rep(NA,na_tail)) ) } # Compute CVE if (cve) { res$cve <- list(s=s_out_orig) if (attr(dat_v, "groups")!="both") { stop("Placebo group not detected.") } ov <- est_overall(dat=dat, t_0=t_0, method=placebo_risk_method, ve=F) risk_p <- ov[ov$group=="placebo","est"] se_p <- ov[ov$group=="placebo","se"] # This equals sd_p/n_vacc res$cve$est <- 1 - res$cr$est/risk_p if (ci_type=="none") { na_vec <- rep(NA, length(res$cve$s_out)) res$cve$se <- na_vec res$cve$ci_lower <- na_vec res$cve$ci_upper <- na_vec } else { # Variance of Chernoff RV var_z <- 0.52^2 # !!!!! Need to do edge_corr # Finite sample corrected SE estimate res$cve$se <- sqrt( ( res$cr$est^2/risk_p^4 ) * se_p^2 + (qnt*tau_ns/(risk_p*n_vacc^(1/3)))^2 * var_z ) if (ci_type=="regular") { res$cve$ci_lower <- res$cve$est - 1.96*res$cve$se res$cve$ci_upper <- res$cve$est + 1.96*res$cve$se } else if (ci_type=="truncated") { res$cve$ci_lower <- pmin(res$cve$est - 1.96*res$cve$se, 1) res$cve$ci_upper <- pmin(res$cve$est + 1.96*res$cve$se, 1) } else if (ci_type=="transformed") { res$cve$ci_lower <- 1 - exp( log(1-res$cve$est) + 1.96*(1/(1-res$cve$est))*res$cve$se ) res$cve$ci_upper <- 1 - exp( log(1-res$cve$est) - 1.96*(1/(1-res$cve$est))*res$cve$se ) } else if (ci_type=="transformed 2") { res$cve$ci_lower <- 1 - exp2( log2(1-res$cve$est) + 1.96*deriv_log2(1-res$cve$est)*res$cve$se ) res$cve$ci_upper <- 1 - exp2( log2(1-res$cve$est) - 1.96*deriv_log2(1-res$cve$est)*res$cve$se ) } # CI edge correction if (p$edge_corr) { # Finite sample corrected SE estimate se_edge_est_cve <- sqrt( (ests_cr[1]^2/risk_p^4)*se_p^2 + (sigma2_edge_est/n_vacc)/(risk_p^2) ) if (ci_type=="regular") { ci_lo_cve2 <- res$cve$est[1] - 1.96*se_edge_est_cve ci_up_cve2 <- res$cve$est[1] + 1.96*se_edge_est_cve } else if (ci_type=="truncated") { ci_lo_cve2 <- min(res$cve$est[1] - 1.96*se_edge_est_cve, 1) ci_up_cve2 <- min(res$cve$est[1] - 1.96*se_edge_est_cve, 1) } else if (ci_type=="transformed") { ci_lo_cve2 <- 1 - exp( log(1-res$cve$est[1]) + 1.96*(1/(1-res$cve$est[1]))*se_edge_est_cve ) ci_up_cve2 <- 1 - exp( log(1-res$cve$est[1]) - 1.96*(1/(1-res$cve$est[1]))*se_edge_est_cve ) } else if (ci_type=="transformed 2") { ci_lo_cve2 <- 1 - exp2( log2(1-res$cve$est[1]) + 1.96*deriv_log2(1-res$cve$est[1])*se_edge_est_cve ) ci_up_cve2 <- 1 - exp2( log2(1-res$cve$est[1]) - 1.96*deriv_log2(1-res$cve$est[1])*se_edge_est_cve ) } if (p$dir=="decr") { res$cve$ci_lower <- ind_edge*pmax(res$cve$ci_lower,ci_lo_cve2) + (1-ind_edge)*res$cve$ci_lower res$cve$ci_upper <- ind_edge*pmax(res$cve$ci_upper,ci_up_cve2) + (1-ind_edge)*res$cve$ci_upper res$cve$ci_lower[1] <- ci_lo_cve2 # !!!!! res$cve$ci_upper[1] <- ci_up_cve2 # !!!!! } else { res$cve$ci_lower <- ind_edge*pmin(res$cve$ci_lower,ci_lo_cve2) + (1-ind_edge)*res$cve$ci_lower res$cve$ci_upper <- ind_edge*pmin(res$cve$ci_upper,ci_up_cve2) + (1-ind_edge)*res$cve$ci_upper res$cve$ci_lower[1] <- ci_lo_cve2 # !!!!! res$cve$ci_upper[1] <- ci_up_cve2 # !!!!! } } if (p$mono_cis) { dir_opposite <- ifelse(p$dir=="decr", "incr", "decr") new_lims <- monotonize_cis( ci_lo = res$cve$ci_lower, ci_up = res$cve$ci_upper, dir = dir_opposite, type = "regular" ) res$cve$ci_lower <- new_lims$ci_lo res$cve$ci_upper <- new_lims$ci_up } } } if (return_extras) { if (attr(dat, "covariates_ph2")) { ind_sample <- sample(c(1:nrow(dat_v2_rd)), size=20) } else { ind_sample <- sample(c(1:nrow(dat_v_rd)), size=20) } s1 <- min(grid$s) s3 <- max(grid$s) s2 <- grid$s[which.min(abs((s3-s1)/2-grid$s))] Q_n_df <- data.frame( "ind" = double(), "t" = double(), "s" = double(), "est" = double() ) Qc_n_df <- Q_n_df for (ind in ind_sample) { for (t in grid$y) { if (attr(dat, "covariates_ph2")) { x_val <- as.numeric(dat_v2_rd[ind,c(1:dim_x)]) } else { x_val <- as.numeric(dat_v_rd[ind,c(1:dim_x)]) } Q_val_s1 <- Q_n(t=t, x=x_val, s=s1) Q_val_s2 <- Q_n(t=t, x=x_val, s=s2) Q_val_s3 <- Q_n(t=t, x=x_val, s=s3) Qc_val_s1 <- Qc_n(t=t, x=x_val, s=s1) Qc_val_s2 <- Qc_n(t=t, x=x_val, s=s2) Qc_val_s3 <- Qc_n(t=t, x=x_val, s=s3) Q_n_df[nrow(Q_n_df)+1,] <- c(ind, t, s1, Q_val_s1) Q_n_df[nrow(Q_n_df)+1,] <- c(ind, t, s2, Q_val_s2) Q_n_df[nrow(Q_n_df)+1,] <- c(ind, t, s3, Q_val_s3) Qc_n_df[nrow(Qc_n_df)+1,] <- c(ind, t, s1, Qc_val_s1) Qc_n_df[nrow(Qc_n_df)+1,] <- c(ind, t, s2, Qc_val_s2) Qc_n_df[nrow(Qc_n_df)+1,] <- c(ind, t, s3, Qc_val_s3) } } if (return_p_value) { res$p <- test_res$p } res$extras <- list( r_Mn = data.frame( s = s_out_orig, est = c(rep(NA,na_head), sapply(s_out, r_Mn), rep(NA,na_tail)) ), deriv_r_Mn = data.frame( s = s_out_orig, est = c(rep(NA,na_head), sapply(s_out, deriv_r_Mn), rep(NA,na_tail)) ), Gamma_os_n = data.frame( s = s_out_orig, est = c(rep(NA,na_head), sapply(s_out, Gamma_os_n), rep(NA,na_tail)) ), f_s_n = data.frame( s = s_out_orig, est = c(rep(NA,na_head), sapply(s_out, f_s_n), rep(NA,na_tail)) ), Q_n = Q_n_df, Qc_n = Qc_n_df ) # !!!!! TEMP if (p$edge_corr) { res$extras$r_Mn_edge_est <- r_Mn_edge_est res$extras$r_Mn_0 <- r_Mn(0) res$extras$r_Mn_Gr_0 <- r_Mn_Gr(0) res$extras$sigma2_edge_est <- sigma2_edge_est res$extras$risk_p <- risk_p res$extras$se_p <- se_p } } return(res) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/est_np.R
#' Estimate overall risk and vaccine efficacy #' #' @description Estimate overall risk and vaccine efficacy. #' @param dat A data object returned by load_data #' @param t_0 Time point of interest #' @param method One of c("KM", "Cox"), corresponding to either a Kaplan-Meier #' estimator ("KM") or a marginalized Cox proportional hazards model #' ("Cox"). #' @param risk Boolean. If TRUE, the controlled risk (CR) curve is computed. #' @param ve Boolean. If TRUE, the controlled vaccine efficacy (CVE) curve is #' computed. #' @return A dataframe containing estimates #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' est_overall(dat=dat, t_0=578, method="KM") #' @export est_overall <- function(dat, t_0, method="Cox", risk=TRUE, ve=TRUE) { # ci_type="transformed" if (!(method %in% c("Cox", "KM")) || length(method)>1) { stop("`method` must equal either 'Cox' or 'KM'.") } if (!methods::is(dat,"vaccine_dat")) { stop(paste0("`dat` must be an object of class 'vaccine_dat' returned by lo", "ad_data().")) } .groups <- attr(dat, "groups") if (.groups=="vaccine" && ve) { warning(paste0("Vaccine efficacy cannot be calculated because `dat` only c", "ontains data from the vaccine group.")) } if (.groups=="placebo" && ve) { warning(paste0("Vaccine efficacy cannot be calculated because `dat` only c", "ontains data from the placebo group.")) } if (.groups=="both") { .groups <- c("vaccine", "placebo") } # Container for results res <- data.frame( "stat" = character(), "group" = character(), "est" = double(), "se" = double(), "ci_lower" = double(), "ci_upper" = double() ) for (grp in .groups) { if (grp=="vaccine") { dat_grp <- dat[dat$a==1,] } else { dat_grp <- dat[dat$a==0,] } if (method=="Cox") { # Alias random variables N <- length(dat_grp$s) dim_x <- attr(dat, "dim_x") X <- dat_grp[,c(1:dim_x), drop=F] V_ <- t(as.matrix(X)) Y_ <- dat_grp$y D_ <- dat_grp$delta dim_v <- dim(V_)[1] # Create set of event times i_ev <- which(D_==1) # Fit an unweighted Cox model model <- survival::coxph( formula = stats::formula(paste0("survival::Surv(y,delta)~", paste(names(X),collapse="+"))), data = cbind(y=Y_, delta=D_, X) ) coeffs <- model$coefficients beta_n <- as.numeric(coeffs) if (any(is.na(coeffs))) { na_coeffs <- names(coeffs)[which(is.na(coeffs))] stop(paste0("The following covariate coefficients were NA.: ", paste(na_coeffs, collapse=","), " Try removing these coefficients and rerunning.")) # !!!!! Automatically omit from the model, as is done for spline coeffs } LIN <- as.numeric(t(beta_n)%*%V_) # Intermediate functions { S_0n <- (function() { .cache <- new.env() function(x) { val <- .cache[[as.character(x)]] if (is.null(val)) { val <- (function(x) { (1/N) * sum(In(Y_>=x)*exp(LIN)) })(x) .cache[[as.character(x)]] <- val } return(val) } })() S_1n <- (function() { .cache <- new.env() function(x) { val <- .cache[[as.character(x)]] if (is.null(val)) { val <- (function(x) { (1/N) * as.numeric(V_ %*% (In(Y_>=x)*exp(LIN))) })(x) .cache[[as.character(x)]] <- val } return(val) } })() S_2n <- (function() { .cache <- new.env() function(x) { val <- .cache[[as.character(x)]] if (is.null(val)) { val <- (function(x) { res <- matrix(NA, nrow=dim_v, ncol=dim_v) for (i in c(1:dim_v)) { for (j in c(1:dim_v)) { if (!is.na(res[j,i])) { res[i,j] <- res[j,i] } else { res[i,j] <- (1/N)*sum(In(Y_>=x)*V_[i,]*V_[j,]*exp(LIN)) } } } return(res) })(x) .cache[[as.character(x)]] <- val } return(val) } })() m_n <- (function() { .cache <- new.env() function(x) { val <- .cache[[as.character(x)]] if (is.null(val)) { val <- S_1n(x) / S_0n(x) .cache[[as.character(x)]] <- val } return(val) } })() } # Estimated information matrix (for an individual) I_tilde <- Reduce("+", lapply(i_ev, function(i) { (S_2n(Y_[i])/S_0n(Y_[i])) - m_n(Y_[i]) %*% t(m_n(Y_[i])) })) I_tilde <- (1/N)*I_tilde I_tilde_inv <- solve(I_tilde) # Score function (Cox model) l_n <- (function() { .cache <- new.env() function(v_i,d_i,y_i) { key <- paste(c(v_i,d_i,y_i), collapse=" ") val <- .cache[[key]] if (is.null(val)) { explin_i <- exp(sum(v_i*beta_n)) val <- d_i*(v_i-m_n(y_i)) - (1/N)*Reduce("+", lapply(i_ev, function(j) { (explin_i*In(Y_[j]<=y_i) * (v_i-m_n(Y_[j]))) / S_0n(Y_[j]) })) .cache[[key]] <- val } return(val) } })() # Influence function: beta_hat (regular Cox model) infl_fn_beta <- function(v_i,d_i,y_i) { I_tilde_inv %*% l_n(v_i,d_i,y_i) } # Nuisance constant: mu_n mu_n <- -1 * (1/N) * as.numeric(Reduce("+", lapply(i_ev, function(j) { (In(Y_[j]<=t_0) * m_n(Y_[j])) / S_0n(Y_[j]) }))) # Breslow estimator Lambda_n <- function(t) { (1/N) * sum(unlist(lapply(i_ev, function(i) { In(Y_[i]<=t) / S_0n(Y_[i]) }))) } # Survival estimator (at a point) Q_n <- (function() { Lambda_n_t_0 <- Lambda_n(t_0) function(z) { exp(-exp(sum(z*beta_n))*Lambda_n_t_0) } })() # Influence function: Breslow estimator (est. weights) infl_fn_Lambda <- (function() { .cache <- new.env() function(v_i,d_i,y_i) { key <- paste(c(v_i,d_i,y_i), collapse=" ") val <- .cache[[key]] if (is.null(val)) { val <- (function(v_i,d_i,y_i) { pc_5 <- sum(mu_n*infl_fn_beta(v_i,d_i,y_i)) pc_1 <- ( d_i * In(y_i<=t_0) ) / S_0n(y_i) explin_i <- exp(sum(beta_n*v_i)) pc_3 <- (1/N) * sum(unlist(lapply(i_ev, function(j) { (In(Y_[j]<=t_0)*In(y_i>=Y_[j])*explin_i) / (S_0n(Y_[j]))^2 }))) return(pc_1+pc_5-pc_3) })(v_i,d_i,y_i) .cache[[key]] <- val } return(val) } })() # Compute marginalized risk res_cox <- list() Lambda_n_t_0 <- Lambda_n(t_0) res_cox$est_marg <- (1/N) * sum((apply(dat_grp, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) exp(-1*exp(sum(beta_n*x_i))*Lambda_n_t_0) }))) # Compute variance estimate res_cox$var_est_marg <- (function() { # Precalculate pieces dependent on s K_n <- (1/N) * Reduce("+", apply2(dat_grp, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) Q <- Q_n(x_i) explin <- exp(sum(x_i*beta_n)) K_n1 <- Q K_n2 <- Q * explin K_n3 <- Q * explin * x_i return(c(K_n1,K_n2,K_n3)) }, simplify=F)) K_n1 <- K_n[1] K_n2 <- K_n[2] K_n3 <- K_n[3:length(K_n)] (1/N^2) * sum((apply(dat_grp, 1, function(r) { x_i <- as.numeric(r[1:dim_x]) z_i <- r[["z"]] d_i <- r[["delta"]] y_i <- r[["y"]] pc_1 <- Q_n(x_i) pc_2 <- Lambda_n_t_0 * sum(K_n3*infl_fn_beta(x_i,d_i,y_i)) pc_3 <- K_n2 * infl_fn_Lambda(x_i,d_i,y_i) pc_4 <- K_n1 return((pc_1-pc_2-pc_3-pc_4)^2) }))) })() # Extract estimates and SEs est <- 1-res_cox$est_marg se <- sqrt(res_cox$var_est_marg) # Generate confidence limits # if (ci_type=="none") { # ci_lo <- NA # ci_up <- NA # } else if (ci_type=="regular") { # ci_lo <- pmin(pmax(est - 1.96*se, 0), 1) # ci_up <- pmin(pmax(est + 1.96*se, 0), 1) # } else if (ci_type=="transformed") { ci_lo <- expit(logit(est) - 1.96*deriv_logit(est)*se) ci_up <- expit(logit(est) + 1.96*deriv_logit(est)*se) # } } if (method=="KM") { srv_p <- survival::survfit(survival::Surv(y,delta)~1, data=dat_grp) est <- 1 - srv_p$surv[which.min(abs(srv_p$time-t_0))] ci_lo <- 1 - srv_p$upper[which.min(abs(srv_p$time-t_0))] ci_up <- 1 - srv_p$lower[which.min(abs(srv_p$time-t_0))] se <- srv_p$std.err[which.min(abs(srv_p$time-t_0))] } # Update results dataframe res[nrow(res)+1,] <- list(stat="risk", group=grp, est=est, se=se, ci_lower=ci_lo, ci_upper=ci_up) } if (ve) { est_v <- res[res$group=="vaccine","est"] est_p <- res[res$group=="placebo","est"] est_ve <- 1-(est_v/est_p) # CIs on the log(1-VE) scale se_v <- res[res$group=="vaccine","se"] se_p <- res[res$group=="placebo","se"] ci_lo <- 1 - exp( log(est_v/est_p) + 1.96*sqrt(se_v^2/est_v^2 + se_p^2/est_p^2) ) ci_up <- 1 - exp( log(est_v/est_p) - 1.96*sqrt(se_v^2/est_v^2 + se_p^2/est_p^2) ) # Standard error on the VE scale se_ve <- sqrt( se_v^2/est_p^2 + (se_p^2*est_v^2)/est_p^4 ) # Update results dataframe res[nrow(res)+1,] <- list(stat="ve", group="both", est=est_ve, se=se_ve, ci_lower=ci_lo, ci_upper=ci_up) } class(res) <- c(class(res), "vaccine_overall") return(res) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/est_overall.R
#' Construct influence function corresponding to r_Mn_edge #' #' @param Q_n Conditional survival function estimator returned by #' `construct_Q_n` #' @param g_sn Propensity score estimator returned by `construct_g_sn` #' @param omega_n A nuisance influence function returned by `construct_omega_n` #' @param r_Mn_edge_est Estimate returned by one-step estimator `r_Mn_edge` #' @return Influence function estimator #' @noRd construct_infl_fn_r_Mn_edge <- function(Q_n, g_sn, omega_n, g_n, r_Mn_edge_est, p_n, t_0) { return(memoise2(function(z, weight, s, x, y, delta) { if (z==0) { s <- 0 pi_ <- 1 } else { pi_ <- 1/weight } return( 1 - Q_n(t_0,x,s=0) + ((z*In(s==0)+g_sn(x,y,delta)*(pi_-z)) * omega_n(x,s=0,y,delta)) / (pi_*(1-p_n)*g_n(s=0,x)) - r_Mn_edge_est ) })) } #' Construct influence function corresponding to Kaplan-Meier estimator #' #' @param dat_combined Combined dataset; !!!!! TEMP #' @return Influence function estimator #' @note Used by est_med() #' @noRd construct_infl_fn_risk_p <- function(dat_p_rd, Q_noS_n, omega_noS_n, t_0, p_plac) { dim_x <- attr(dat_p_rd, "dim_x") mean_Q_n <- mean(apply(dat_p_rd, 1, function(r) { Q_noS_n(t_0,as.numeric(r[1:dim_x])) })) infl_fn <- function(a,delta,y,x) { if (a==1) { return(0) } else { return((1/p_plac)*(omega_noS_n(x,y,delta)-Q_noS_n(t_0,x)+mean_Q_n)) } } return(infl_fn) } #' Construct influence function corresponding to Kaplan-Meier estimator #' #' @param dat_combined Combined dataset; !!!!! TEMP #' @return Influence function estimator #' @note Used by est_med() #' @noRd construct_infl_fn_risk_v <- function(dat_v_rd, Q_n, g_n, omega_n, q_tilde_n, t_0, p_vacc) { dat_v2_rd <- dat_v_rd[dat_v_rd$z==1,] n_vacc <- attr(dat_v_rd, "n_vacc") dim_x <- attr(dat_v_rd, "dim_x") # Helper function C_n <- memoise2(function(s) { mean(apply(dat_v_rd, 1, function(r) { x <- as.numeric(r[1:dim_x]) return(Q_n(t_0,x,s)*g_n(s,x)) })) }) mean_Q_n_g_n <- (1/n_vacc) * sum(apply(dat_v2_rd, 1, function(r) { r[["weights"]] * C_n(r[["s"]]) # Replace with sapply })) infl_fn <- function(a,z,weight,s,x,y,delta) { if (a==0) { return(0) } else { if (z==0) { s <- 0 pi_ <- 1 } else { pi_ <- 1/weight } val <- (z/pi_)*(omega_n(x,s,y,delta)-Q_n(t_0,x,s)) + (1-z/pi_)*q_tilde_n(x,y,delta) + mean_Q_n_g_n return((1/p_vacc)*val) } } return(memoise2(infl_fn)) } #' Construct influence function corresponding to Kaplan-Meier estimator #' #' @param dat_combined Combined dataset; !!!!! TEMP #' @return Influence function estimator #' @note Used by est_med() #' @noRd construct_infl_fn_risk_v_v2 <- function(dat_v_rd, Q_noS_n_v, omega_noS_n_v, t_0, p_vacc) { dim_x <- attr(dat_v_rd, "dim_x") mean_Q_n <- mean(apply(dat_v_rd, 1, function(r) { Q_noS_n_v(t_0,as.numeric(r[1:dim_x])) })) infl_fn <- function(a,delta,y,x) { if (a==0) { return(0) } else { return((1/p_vacc)*(omega_noS_n_v(x,y,delta)-Q_noS_n_v(t_0,x)+mean_Q_n)) } } return(infl_fn) } #' !!!!! document #' #' @param x x #' @return x #' @noRd construct_infl_fn_Theta <- function(omega_n, f_sIx_n, q_tilde_n, etastar_n, Theta_os_n) { fnc <- function(u,x,y,delta,s,weight) { if (weight==0) { piece_1 <- 0 piece_2 <- 0 } else { piece_1 <- In(s<=u) piece_2 <- omega_n(x,s,y,delta)/f_sIx_n(s,x) } weight*piece_1*piece_2 + (1-weight) * q_tilde_n(x,y,delta,u) + etastar_n(u,x) - Theta_os_n(u) } return(memoise2(fnc)) } #' !!!!! document #' #' @param x x #' @return x #' @noRd construct_infl_fn_beta_n <- function(infl_fn_Theta) { u_mc <- round(seq(0.01,1,0.01),2) m <- length(u_mc) lambda_1 <- mean(u_mc) # ~1/2 lambda_2 <- mean((u_mc)^2) # ~1/3 lambda_3 <- mean((u_mc)^3) # ~1/4 piece_1 <- lambda_1*lambda_2-lambda_3 piece_2 <- lambda_2-lambda_1^2 fnc <- function(s,y,delta,weight,x) { return((1/m) * sum(sapply(u_mc, function(u) { infl_fn_Theta(u,x,y,delta,s,weight) * (piece_1*(u-lambda_1)+piece_2*(u^2-lambda_2)) }))) } return(memoise2(fnc)) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/influence_functions.R
##' Load and format data object #' #' @description This function takes in user-supplied data and returns a data #' object that can be read in by \code{\link{summary_stats}}, #' \code{\link{est_ce}}, \code{\link{est_med}}, and other estimation #' functions. Data is expected to come from a vaccine clinical trial, #' possibly involving two-phase sampling and possibly including a biomarker #' of interest. #' @param time A character string; the name of the numeric variable representing #' observed event or censoring times. #' @param event A character string; the name of the binary variable #' corresponding to whether the observed time represents an event time (1) #' or a censoring time (0). Either integer (0/1) or Boolean (T/F) values are #' allowed. #' @param vacc A character string; the name of the binary variable denoting #' whether the individual is in the vaccine group (1) or the placebo group #' (0). Accepts either integer (0/1) or Boolean (T/F) values. #' @param marker A character string; the name of the numeric variable of #' biomarker values. #' @param covariates A character vector; the names of the covariate columns. #' Columns values should be either numeric, binary, or factors. Character #' columns will be converted into factors. #' @param weights A character string; the name of the numeric variable #' containing inverse-probability-of-sampling (IPS) weights. #' @param ph2 A character string; the name of the binary variable representing #' whether the individual is in the phase-two cohort (1) or not (0). Accepts #' either integer (0/1) or Boolean (T/F) values. #' @param strata A character string; the name of the variable containing strata #' identifiers (for two-phase sampling strata). #' @param data A dataframe containing the vaccine trial data. #' @param covariates_ph2 A boolean; if at least one of the covariates is #' measured only in the phase-two cohort, set this to TRUE. #' @return An object of class \code{vaccine_dat}. #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' @export load_data <- function( time, event, vacc, marker, covariates, weights, ph2, strata=NA, data, covariates_ph2=FALSE ) { # To prevent R CMD CHECK notes .time <- .marker <- .covariates <- NULL; rm(.time,.marker,.covariates); # Input validation { if (!methods::is(data,"data.frame")) { stop("`data` must be a data frame.") } if (nrow(data)==0) { stop("`data` is an empty data frame.") } for (arg in c("time", "event", "vacc", "marker", "covariates", "weights", "ph2", "strata")) { var <- get(arg) if (!(arg=="strata" && missing(strata))) { # if (!(arg=="strata")) { # For testing # Variable is a character string specifying variable(s) in `data` is_string <- methods::is(var,"character") length_one <- as.logical(length(var)==1) in_df <- all(as.logical(var %in% names(data))) if (arg=="covariates") { if (!(is_string&&in_df)) { stop(paste0("`", arg, "` must be a vector of character strings spe", "cifying one or more variables in `data`.")) } } else { if (!(is_string&&length_one&&in_df)) { stop(paste0("`", arg, "` must be a character string specifying a s", "ingle variable in `data`.")) } } # Assign column(s) to val if (arg=="covariates") { val <- data[,var, drop=F] val2 <- list() # Convert factor/character columns for (col in names(val)) { if (is.numeric(val[,col])) { val2[[col]] <- val[,col] } else if (is.logical(val[,col])) { val2[[col]] <- as.integer(val[,col]) } else if (is.factor(val[,col]) || is.character(val[,col])) { tmp_col <- as.integer(as.factor(val[,col])) tmp_unique <- unique(tmp_col) tmp_size <- length(tmp_unique) for (i in c(1:tmp_size)) { col_new <- paste0(col, "_", i) val2[[col_new]] <- as.integer(tmp_col==tmp_unique[i]) } } else { stop(paste0("The data type of column `", col, "` is not supported.")) } } val <- as.data.frame(val2) x_names <- names(val) } else { val <- data[,var] } # Validate: `time`, `marker`, `weights` if (arg %in% c("time", "marker", "weights")) { if (!is.numeric(val)) { stop(paste0("`", arg, "` must be numeric.")) } } # Validate: `event`, `vacc`, `ph2` if (arg %in% c("event", "vacc", "ph2")) { if (any(!(val %in% c(0,1,F,T)))) { stop(paste0("`", arg, "` must only contain binary values (either T", "/F or 1/0).")) } } # No missing values allowed (except marker) if (!(arg %in% c("marker", "weights", "covariates"))) { if (any(is.na(val))) { stop("NA values not allowed in `", arg, "`.") } } else if (arg=="covariates") { cond_1 <- any(is.na(val)) cond_2 <- any(is.na(val[as.logical(data[,ph2]),])) msg_1 <- "NA values not allowed in `covariates` (if covariates_ph2==F)." msg_2 <- paste0("NA values only allowed in `covariates` for which ph2==F (if covariates_ph2==T).") if (cond_1 && !covariates_ph2) { stop(msg_1) } if (cond_2 && covariates_ph2) { stop(msg_2) } } assign(x=paste0(".",arg), value=val) } else { .strata <- NA } } } # Convert binary variables to integers (if specified as boolean) .event <- as.integer(.event) .vacc <- as.integer(.vacc) .ph2 <- as.integer(.ph2) # Create additional variables .groups <- ifelse(any(.vacc==0) && any(.vacc==1), "both", ifelse(any(.vacc==1), "vaccine", "placebo")) .weights <- ifelse(is.na(.weights), 0, .weights) .dim_x <- length(.covariates) .n_v <- sum(.vacc) .n_p <- sum(1-.vacc) # Rename covariate dataframe to c("x1", "x2", ...) names(.covariates) <- paste0("x", c(1:.dim_x)) # !!!!! Warning/error if there is only one unique level or too many (>15) unique levels # !!!!! Warning/error if there are numbers passed in as character strings # !!!!! Check what processing we have to do to strata (e.g. convert to integers) # !!!!! Convert booleans to integers (0 or 1) for all coolumns (incl covariates) # !!!!! Store two copies of covariates; one for Cox model and one for NPCVE etc. # !!!!! Also maybe store a combined version of the dataset (or have a helper function to combine)? if (.groups %in% c("vaccine", "both")) { # Create strata (if not given) .ind_v <- which(.vacc==1) if(is.na(.strata[[1]])) { .strata <- as.integer(factor(.weights[.ind_v])) } else { .strata <- as.integer(factor(.strata[.ind_v])) } # Create data object df_v <- cbind( .covariates[.ind_v,, drop=F], "y"=.time[.ind_v], "delta"=.event[.ind_v], "s"=.marker[.ind_v], "weights"=.ph2[.ind_v]*.weights[.ind_v], "strata"=.strata, "z"=.ph2[.ind_v], "a"=1 ) # Stabilize weights (rescale to sum to sample size) .stb_v <- sum(df_v$weights) / .n_v df_v$weights <- df_v$weights / .stb_v } if (.groups %in% c("placebo", "both")) { # Create strata (if not given) .ind_p <- which(.vacc==0) if(is.na(.strata[[1]])) { .strata <- as.integer(factor(.weights[.ind_p])) } else { .strata <- as.integer(factor(.strata[.ind_p])) } # Create data object df_p <- cbind( .covariates[.ind_p,, drop=F], "y"=.time[.ind_p], "delta"=.event[.ind_p], "s"=.marker[.ind_p], "weights"=.ph2[.ind_p]*.weights[.ind_p], "strata"=.strata, "z"=.ph2[.ind_p], "a"=0 ) # Stabilize weights (rescale to sum to sample size) # !!!!! Consider making weights NA in placebo group .stb_p <- sum(df_p$weights) / .n_p df_p$weights <- df_p$weights / .stb_p } if (.groups=="vaccine") { dat <- df_v } else if (.groups=="placebo") { dat <- df_p } else if (.groups=="both") { dat <- rbind(df_v, df_p) } # Create and return data object class(dat) <- c("data.frame", "vaccine_dat") attr(dat, "groups") <- .groups attr(dat, "covariate_names") <- x_names attr(dat, "covariates_ph2") <- covariates_ph2 attr(dat, "dim_x") <- .dim_x attr(dat, "n") <- .n_v+.n_p attr(dat, "n_vacc") <- .n_v attr(dat, "n_vacc2") <- sum(df_v$z) attr(dat, "n_plac") <- .n_p return(dat) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/load_data.R
#' Various elementary functions #' #' @param x Numeric input #' @return Numeric output #' @noRd logit <- function(x) { log(x/(1-x)) } expit <- function(x) { 1 / (1+exp(-x)) } expit2 <- function(x) { (expit(x)-0.001)/0.998 } logit2 <- function(x) { logit(0.001+0.998*x) } log2 <- function(x) { log(x+0.001) } exp2 <- function(x) { exp(x) - 0.001 } deriv_expit <- function(x) { exp(x) / ((1+exp(x))^2) } deriv_logit <- function(x) { 1 / (x-x^2) } deriv_logit2 <- function(x) { 0.998*deriv_logit(0.001+0.998*x) } deriv_log2 <- function(x) { 1 / (x+0.001) } #' Alias for indicator (as.integer) function #' #' @noRd In <- as.integer #' Helper function for debugging; prints timestamps #' #' @noRd chk <- function(num, msg="") { if (msg=="") { str <- paste0("Check ", num, ": ", Sys.time()) } else { str <- paste0("Check ", num, " (", msg, "): ", Sys.time()) } message(str) } #' Memoise a function #' #' @param fnc A function to be memoised #' @return Memoised version of function #' @note #' - This is a lightweight/faster version of the `memoise` function #' @noRd memoise2 <- function(fnc) { htab <- new.env() ..new_fnc <- function() { ..e <- parent.env(environment()) ..mc <- lapply(as.list(match.call())[-1L], eval, parent.frame()) key <- rlang::hash(..mc) val <- ..e$htab[[key]] if (is.null(val)) { val <- do.call(..e$fnc, ..mc) ..e$htab[[key]] <- val } return(val) } # Set formals and set up environment formals(..new_fnc) <- formals(fnc) f_env <- new.env(parent=environment(fnc)) f_env$arg_names <- names(formals(fnc)) f_env$htab <- htab f_env$fnc <- fnc environment(..new_fnc) <- f_env return(..new_fnc) } #' Round data values #' #' @param dat Dataset returned by `load_data` (possibly filtered) #' @param grid_size A list, as specified in `params_ce_np` #' @return Dataset with values rounded #' @noRd create_grid <- function(dat, grid_size, t_0) { grid <- list() grid$y <- round(seq(from=0, to=t_0, length.out=grid_size$y), 5) grid$y_ext <- round(seq(from=0, to=max(dat$y), by=(t_0/(grid_size$y-1))), 5) if (!(t_0 %in% grid$y)) { grid$y <- sort(c(grid$y, t_0)) } grid$s <- round(seq(from=0, to=1, length.out=grid_size$s), 5) grid$x <- lapply(c(1:attr(dat,"dim_x")), function(i) { x_col <- as.numeric(dat[,i]) if (length(unique(x_col[!is.na(x_col)]))>grid_size$x) { return(round(seq(from=min(x_col, na.rm=T), to=max(x_col, na.rm=T), length.out=grid_size$x), 5)) } else { return(NA) } }) return(grid) } #' Round data values #' #' @param dat Dataset returned by `load_data` (possibly filtered) #' @param grid A grid, returned by `create_grid` #' @param grid_size A list, as specified in `est_np` #' @return Dataset with values rounded #' @noRd round_dat <- function(dat, grid, grid_size) { # Round `y` and `s` dat$y <- sapply(dat$y, function(y) { grid$y_ext[which.min(abs(grid$y_ext-y))] }) dat$s <- sapply(dat$s, function(s) { if (is.na(s)) { return(NA) } else { return(grid$s[which.min(abs(grid$s-s))]) } }) # Round `x` for (i in c(1:attr(dat,"dim_x"))) { x_col <- as.numeric(dat[,i]) if (length(unique(x_col[!is.na(x_col)]))>grid_size$x) { dat[,i] <- sapply(x_col, function(x) { if (is.na(x)) { return(NA) } else { return(grid$x[[i]][which.min(abs(grid$x[[i]]-x))]) } }) } } # !!!!! Note: not rounding weights (for now) return(dat) } #' Find dataframe index of a row #' #' @param vec A numeric vector #' @param df A dataframe to search #' @return The index of the row of `df` at which `vec` is found #' @noRd find_index <- function(vec, df) { vec <- as.numeric(vec) r <- list() for (i in c(1:length(vec))) { r[[i]] <- which(abs(vec[i]-df[,i])<1e-8) } index <- Reduce(intersect, r) if (length(index)!=1) { if (length(index)==0) { stop("length(index)==0") } if (length(index)>1) { stop("length(index)>1") } } return(index) } #' Copy of apply function #' #' @noRd apply2 <- function (X, MARGIN, FUN, ..., simplify=TRUE) { FUN <- match.fun(FUN) simplify <- isTRUE(simplify) dl <- length(dim(X)) if (!dl) stop("dim(X) must have a positive length") if (is.object(X)) X <- if (dl == 2L) as.matrix(X) else as.array(X) d <- dim(X) dn <- dimnames(X) ds <- seq_len(dl) if (is.character(MARGIN)) { if (is.null(dnn <- names(dn))) stop("'X' must have named dimnames") MARGIN <- match(MARGIN, dnn) if (anyNA(MARGIN)) stop("not all elements of 'MARGIN' are names of dimensions") } d.call <- d[-MARGIN] d.ans <- d[MARGIN] if (anyNA(d.call) || anyNA(d.ans)) stop("'MARGIN' does not match dim(X)") s.call <- ds[-MARGIN] s.ans <- ds[MARGIN] dn.call <- dn[-MARGIN] dn.ans <- dn[MARGIN] d2 <- prod(d.ans) if (d2 == 0L) { newX <- array(vector(typeof(X), 1L), dim = c(prod(d.call), 1L)) ans <- forceAndCall(1, FUN, if (length(d.call) < 2L) newX[, 1] else array(newX[, 1L], d.call, dn.call), ...) return(if (is.null(ans)) ans else if (length(d.ans) < 2L) ans[1L][-1L] else array(ans, d.ans, dn.ans)) } newX <- aperm(X, c(s.call, s.ans)) dim(newX) <- c(prod(d.call), d2) ans <- vector("list", d2) if (length(d.call) < 2L) { if (length(dn.call)) dimnames(newX) <- c(dn.call, list(NULL)) for (i in 1L:d2) { tmp <- forceAndCall(1, FUN, newX[, i], ...) if (!is.null(tmp)) ans[[i]] <- tmp } } else for (i in 1L:d2) { tmp <- forceAndCall(1, FUN, array(newX[, i], d.call, dn.call), ...) if (!is.null(tmp)) ans[[i]] <- tmp } ans.list <- !simplify || is.recursive(ans[[1L]]) l.ans <- length(ans[[1L]]) ans.names <- names(ans[[1L]]) if (!ans.list) ans.list <- any(lengths(ans) != l.ans) if (!ans.list && length(ans.names)) { all.same <- vapply(ans, function(x) identical(names(x), ans.names), NA) if (!all(all.same)) ans.names <- NULL } len.a <- if (ans.list) d2 else length(ans <- unlist(ans, recursive = FALSE)) if (length(MARGIN) == 1L && len.a == d2) { names(ans) <- if (length(dn.ans[[1L]])) dn.ans[[1L]] ans } else if (len.a == d2) array(ans, d.ans, dn.ans) else if (len.a && len.a%%d2 == 0L) { if (is.null(dn.ans)) dn.ans <- vector(mode = "list", length(d.ans)) dn1 <- list(ans.names) if (length(dn.call) && !is.null(n1 <- names(dn <- dn.call[1])) && nzchar(n1) && length(ans.names) == length(dn[[1]])) names(dn1) <- n1 dn.ans <- c(dn1, dn.ans) array(ans, c(len.a%/%d2, d.ans), if (!is.null(names(dn.ans)) || !all(vapply(dn.ans, is.null, NA))) dn.ans) } else ans } #' Monotonize confidence limits (NP estimator) #' #' @param ci_lo A vector of confidence interval lower limits #' @param ci_up A vector of confidence interval upper limits #' @param dir Direction of monotonicity; one of c("decr", "incr") #' @param type One of c("regular", "conservative") #' @return A list of the form list(ci_lo=c(), ci_up=c()) #' @noRd monotonize_cis <- function(ci_lo, ci_up, dir, type="regular") { # This helper function returns the "least nondecreasing majorant" lnm <- function(y) { val <- y[1] for (i in c(2:length(y))) { if (!is.na(y[i]) && !is.na(val) && y[i]<val) { y[i] <- val } val <- y[i] } return(y) } if (type=="regular") { if (dir=="decr") { ci_lo <- rev(lnm(rev(ci_lo))) ci_up <- -1*lnm(-1*ci_up) } else { ci_lo <- lnm(ci_lo) ci_up <- -1*rev(lnm(rev(-1*ci_up))) } } else if (type=="conservative") { if (dir=="decr") { ci_lo <- -1*lnm(-1*ci_lo) ci_up <- rev(lnm(rev(ci_up))) } else { ci_lo <- -1*rev(lnm(rev(-1*ci_lo))) ci_up <- lnm(ci_up) } } return(list(ci_lo=ci_lo, ci_up=ci_up)) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/misc_functions.R
# !!!!! TO DO: update docs throughout #' Construct conditional survival estimator Q_n #' #' @param type One of c("true", "Cox", "Random Forest", "Super Learner") #' @param dat Subsample of dataset returned by `ss` for which z==1 #' @param vals List of values to pre-compute function on; REQUIRED FOR SUPERLEARNER #' @param return_model Logical; if TRUE, return the model object instead of the #' function #' @return Conditional density estimator function #' #' @noRd construct_Q_n <- function(type, dat_v, vals, return_model=F) { dim_x <- attr(dat_v,"dim_x") if (type=="Cox") { if (F) { weights <- NA } # Prevents CRAN error x_names <- names(dat_v)[1:dim_x] dat_v$delta2 <- 1 - dat_v$delta model_srv <- survival::coxph( formula = stats::formula(paste0("survival::Surv(y,delta)~", paste(x_names,collapse="+"),"+s")), data = dat_v, weights = weights ) coeffs_srv <- as.numeric(model_srv$coefficients) bh_srv <- survival::basehaz(model_srv, centered=F) model_cens <- survival::coxph( formula = stats::formula(paste0("survival::Surv(y,delta2)~", paste(x_names,collapse="+"),"+s")), data = dat_v, weights = weights ) coeffs_cens <- as.numeric(model_cens$coefficients) bh_cens <- survival::basehaz(model_cens, centered=F) fnc_srv <- function(t, x, s) { if (t==0) { return(1) } else { Lambda_t <- bh_srv$hazard[which.min(abs(bh_srv$time-t))] return(exp(-1*Lambda_t*exp(sum(coeffs_srv*as.numeric(c(x,s)))))) } } fnc_cens <- function(t, x, s) { if (t==0) { return(1) } else { Lambda_t <- bh_cens$hazard[which.min(abs(bh_cens$time-t))] return(exp(-1*Lambda_t*exp(sum(coeffs_cens*as.numeric(c(x,s)))))) } } rm(model_srv) rm(model_cens) } else { do.call("library", list("SuperLearner")) } if (type=="survSL") { # Excluding "survSL.rfsrc" for now. survSL.pchSL gives errors. methods <- c("survSL.coxph", "survSL.expreg", "survSL.km", "survSL.loglogreg", "survSL.pchreg", "survSL.weibreg") # Prevents CRAN Note if (F) { # x <- earth::earth # x <- glmnet::glmnet x <- e1071::svm } newX <- cbind(vals$x, s=vals$s)[which(vals$t==0),] new.times <- unique(vals$t) # Temporary (until survSuperLearner is on CRAN) survSuperLearner <- function() {} rm(survSuperLearner) tryCatch( expr = { do.call("library", list("survSuperLearner")) }, error = function(e) { stop(paste0( "To use surv_type='survSL', you must install the `survSuperLearner` ", "package from github, using:\n\ndevtools::install_github(repo='tedwe", "stling/survSuperLearner')")) } ) srv <- suppressWarnings(survSuperLearner( time = dat_v$y, event = dat_v$delta, X = dat_v[,c(1:dim_x,which(names(dat_v)=="s"))], newX = newX, new.times = new.times, event.SL.library = methods, cens.SL.library = methods, obsWeights = dat_v$weights, control = list(initWeightAlg=methods[1], max.SL.iter=10) )) srv_pred <- srv$event.SL.predict cens_pred <- srv$cens.SL.predict rm(srv) fnc_srv <- function(t, x, s) { row <- find_index(c(x,s), newX) col <- which.min(abs(t-new.times)) if (length(col)!=1) { stop("length(col)!=1") } return(srv_pred[row,col]) } fnc_cens <- function(t, x, s) { row <- find_index(c(x,s), newX) col <- which.min(abs(t-new.times)) if (length(col)!=1) { stop("length(col)!=1") } # Note: the max() function is to prevent unreasonably small censoring # probabilities from destabilizing estimates return(max(cens_pred[row,col], 0.001)) } } if (type %in% c("survML-G","survML-L")) { newX <- cbind(vals$x, s=vals$s)[which(vals$t==0),] new.times <- unique(vals$t) survML_args <- list( time = dat_v$y, event = dat_v$delta, X = dat_v[,c(1:dim_x,which(names(dat_v)=="s"))], newX = newX, newtimes = new.times, bin_size = 0.05, time_basis = "continuous", SL_control = list( # SL.library = rep(c("SL.mean", "SL.glm", "SL.gam", "SL.earth"),2), # Note: rep() is to avoid a SuperLearner bug SL.library = rep(c("SL.mean", "SL.glm", "SL.gam"),2), # Note: rep() is to avoid a SuperLearner bug V = 5, obsWeights = dat_v$weights ) ) if (type=="survML-G") { fit <- suppressWarnings(do.call(survML::stackG, survML_args)) srv_pred <- fit$S_T_preds cens_pred <- fit$S_C_preds } else if (type=="survML-L") { survML_args2 <- survML_args survML_args2$event <- round(1 - survML_args2$event) fit_s <- suppressWarnings(do.call(survML::stackL, survML_args)) fit_c <- suppressWarnings(do.call(survML::stackL, survML_args2)) srv_pred <- fit_s$S_T_preds cens_pred <- fit_c$S_T_preds } fnc_srv <- function(t, x, s) { row <- find_index(c(x,s), newX) col <- which.min(abs(t-new.times)) if (length(col)!=1) { stop("length(col)!=1") } return(srv_pred[row,col]) } fnc_cens <- function(t, x, s) { row <- find_index(c(x,s), newX) col <- which.min(abs(t-new.times)) if (length(col)!=1) { stop("length(col)!=1") } # Note: the max() function is to prevent unreasonably small censoring # probabilities from destabilizing estimates return(max(cens_pred[row,col], 0.001)) } } if (type=="Cox") { sfnc_srv <- fnc_srv sfnc_cens <- fnc_cens } else { sfnc_srv <- memoise2(fnc_srv) sfnc_cens <- memoise2(fnc_cens) } rm("vals", envir=environment(get("fnc_srv",envir=environment(sfnc_srv)))) return(list(srv=sfnc_srv, cens=sfnc_cens)) } #' Construct conditional survival estimator Q_n #' #' @param type One of c("true", "Cox", "Random Forest", "Super Learner") #' @param dat Subsample of dataset returned by `ss` for which z==1 #' @param vals List of values to pre-compute function on; REQUIRED FOR SUPERLEARNER #' @param return_model Logical; if TRUE, return the model object instead of the #' function #' @return Conditional density estimator function #' #' @noRd construct_Q_noS_n <- function(type, dat, vals, return_model=F) { dim_x <- attr(dat,"dim_x") # if (type=="Cox") { if (type %in% c("Cox", "survML-G", "survML-L")) { # !!!!! Temporary to avoid R-CMD-CHECK failure x_names <- names(dat)[1:dim_x] dat$delta2 <- 1 - dat$delta model_srv <- survival::coxph( formula = stats::formula(paste0("survival::Surv(y,delta)~", paste(x_names,collapse="+"))), data = dat ) coeffs_srv <- as.numeric(model_srv$coefficients) bh_srv <- survival::basehaz(model_srv, centered=F) model_cens <- survival::coxph( formula = stats::formula(paste0("survival::Surv(y,delta2)~", paste(x_names,collapse="+"))), data = dat ) coeffs_cens <- as.numeric(model_cens$coefficients) bh_cens <- survival::basehaz(model_cens, centered=F) fnc_srv <- function(t, x) { if (t==0) { return(1) } else { Lambda_t <- bh_srv$hazard[which.min(abs(bh_srv$time-t))] return(exp(-1*Lambda_t*exp(sum(coeffs_srv*as.numeric(x))))) } } fnc_cens <- function(t, x) { if (t==0) { return(1) } else { Lambda_t <- bh_cens$hazard[which.min(abs(bh_cens$time-t))] return(exp(-1*Lambda_t*exp(sum(coeffs_cens*as.numeric(x))))) } } rm(model_srv) rm(model_cens) } else { do.call("library", list("SuperLearner")) } if (type=="survSL") { # Excluding "survSL.rfsrc" for now. survSL.pchSL gives errors. methods <- c("survSL.coxph", "survSL.expreg", "survSL.km", "survSL.loglogreg", "survSL.pchreg", "survSL.weibreg") newX <- vals$x[which(vals$t==0),, drop=F] new.times <- unique(vals$t) # Temporary (until survSuperLearner is on CRAN) survSuperLearner <- function() {} rm(survSuperLearner) tryCatch( expr = { do.call("library", list("survSuperLearner")) }, error = function(e) { stop(paste0( "To use surv_type='survSL', you must install the `survSuperLearner` ", "package from github, using:\n\ndevtools::install_github(repo='tedwe", "stling/survSuperLearner')")) } ) srv <- suppressWarnings(survSuperLearner( time = dat$y, event = dat$delta, X = dat[,c(1:dim_x), drop=F], newX = newX, new.times = new.times, event.SL.library = methods, cens.SL.library = methods, control = list(initWeightAlg=methods[1], max.SL.iter=10) )) srv_pred <- srv$event.SL.predict cens_pred <- srv$cens.SL.predict rm(srv) fnc_srv <- function(t, x) { row <- find_index(x, newX) col <- which.min(abs(t-new.times)) if (length(col)!=1) { stop("length(col)!=1") } return(srv_pred[row,col]) } fnc_cens <- function(t, x) { row <- find_index(x, newX) col <- which.min(abs(t-new.times)) if (length(col)!=1) { stop("length(col)!=1") } # Note: the max() function is to prevent unreasonably small censoring # probabilities from destabilizing estimates return(max(cens_pred[row,col], 0.001)) } } if (type=="Cox") { sfnc_srv <- fnc_srv sfnc_cens <- fnc_cens } else { sfnc_srv <- memoise2(fnc_srv) sfnc_cens <- memoise2(fnc_cens) } rm("vals", envir=environment(get("fnc_srv",envir=environment(sfnc_srv)))) return(list(srv=sfnc_srv, cens=sfnc_cens)) } #' Construct estimator of nuisance influence function omega_n #' #' @param Q_n Conditional survival function estimator returned by #' `construct_Q_n` #' @param Qc_n Conditional censoring survival function estimator returned by #' `construct_Q_n` #' @param type Defaults to "estimated". Override with "true" for debugging. Note #' that type="true" only works for surv_true="Cox" and assumes that Q_0 #' and Qc_0 (i.e. the true functions) are passed in. #' @return Estimator function of nuisance omega_0 #' @noRd construct_omega_n <- function(Q_n, Qc_n, t_0, grid) { # Construct cumulative hazard estimator H_n <- function(t,x,s) { -1 * log(Q_n(t,x,s)) } # Construct memoised integral function x_vals <- memoise2(function(x,s) { diff(sapply(grid$y, function(t) { H_n(t,x,s) })) }) y_vals <- memoise2(function(x,s) { sapply(grid$y[2:length(grid$y)], function(t) { ( Q_n(t,x,s) * Qc_n(t,x,s) )^-1 }) }) omega_integral <- function(k,x,s) { index <- which.min(abs(k-grid$y)) - 1 if (index==0) { return(0) } else { return(sum(x_vals(x,s)[1:index]*y_vals(x,s)[1:index])) } } # omega_integral <- memoise2(omega_integral) # !!!!! Does this make a difference (for profiling)? fnc <- function(x,s,y,delta) { Q_n(t_0,x,s) * ( (delta * In(y<=t_0)) / (Q_n(y,x,s) * Qc_n(y,x,s)) - omega_integral(min(y,t_0),x,s) ) } return(memoise2(fnc)) } #' Construct estimator of nuisance influence function omega_n #' #' @param Q_noS_n Conditional survival function estimator returned by #' `construct_Q_noS_n` (no biomarker) #' @param Qc_noS_n Conditional censoring survival function estimator returned by #' `construct_Q_noS_n` (no biomarker) #' @param type Defaults to "estimated". Override with "true" for debugging. Note #' that type="true" only works for surv_true="Cox" and assumes that Q_0 #' and Qc_0 (i.e. the true functions) are passed in. #' @return Estimator function of nuisance omega_0 #' @noRd construct_omega_noS_n <- function(Q_noS_n, Qc_noS_n, t_0, grid) { Q_n <- Q_noS_n Qc_n <- Qc_noS_n # Construct cumulative hazard estimator H_n <- function(t,x) { -1 * log(Q_n(t,x)) } # Construct memoised integral function x_vals <- memoise2(function(x) { diff(sapply(grid$y, function(t) { H_n(t,x) })) }) y_vals <- memoise2(function(x) { sapply(grid$y[2:length(grid$y)], function(t) { ( Q_n(t,x) * Qc_n(t,x) )^-1 }) }) omega_integral <- function(k,x) { index <- which.min(abs(k-grid$y)) - 1 if (index==0) { return(0) } else { return(sum(x_vals(x)[1:index]*y_vals(x)[1:index])) } } fnc <- function(x,y,delta) { Q_n(t_0,x) * ( (delta * In(y<=t_0)) / (Q_n(y,x) * Qc_n(y,x)) - omega_integral(min(y,t_0),x) ) } return(memoise2(fnc)) } #' Construct estimator of conditional density of S given X #' #' @param dat_v2 Dataset returned by `load_data`, subset to ph2 vacc #' @param type One of c("parametric", "binning") #' @param k Number of bins for the binning estimator (if k=0, then the number of #' bins will be selected via cross-validation); ignored for the parametric #' estimator #' @param z1 Compute the density conditional on Z=1 #' @return Conditional density estimator function #' @note #' - Assumes support of S is [0,1] #' @noRd construct_f_sIx_n <- function(dat_v2, type, k=0, z1=F) { dim_x <- attr(dat_v2, "dim_x") n_vacc2 <- attr(dat_v2, "n_vacc2") if (z1) { dat_v2$weights <- rep(1, length(dat_v2$weights)) } if (type=="parametric") { # Density for a single observation dens_s <- function(s, x, prm) { mu <- sum( c(1,x) * c(expit(prm[1]),prm[2:(length(x)+1)]) ) sigma <- 10*expit(prm[length(prm)]) return( truncnorm::dtruncnorm(s, a=0, b=1, mean=mu, sd=sigma) ) } # Set up weighted likelihood wlik <- function(prm) { -1 * sum(dat_v2$weights * apply(dat_v2, 1, function(r) { log(pmax(dens_s(s=r[["s"]], x=as.numeric(r[1:dim_x]), prm), 1e-8)) })) } # Run optimizer opt <- Rsolnp::solnp( pars = c(rep(0, dim_x+1), 0.15), fun = wlik ) if (opt$convergence!=0) { warning("f_sIx_n: Rsolnp::solnp() did not converge") } prm <- opt$pars # Remove large intermediate objects rm(dat_v2,dens_s,opt) fnc <- function(s, x) { mu <- sum( c(1,x) * c(expit(prm[1]),prm[2:(length(x)+1)]) ) sigma <- 10*expit(prm[length(prm)]) return( truncnorm::dtruncnorm(s, a=0, b=1, mean=mu, sd=sigma) ) } } if (type=="parametric (edge) 2") { # Density for a single observation dens_s <- function(s, x, prm) { mu <- sum( c(1,x) * c(expit(prm[1]),prm[2:(length(x)+1)]) ) sigma <- 10*expit(prm[round(length(x)+2)]) # !!!!! Try using exp instead of expit return(truncnorm::dtruncnorm(s, a=0.01, b=1, mean=mu, sd=sigma)) } # Probability P(S=s|X=x) for s==0 or s!=0 prob_s <- function(s, x, prm) { s <- ifelse(s==0, 0, 1) lin <- sum(c(1,x)*prm) return(expit(lin)^(1-s)*(1-expit(lin))^s) } # Set up weighted likelihood (edge) wlik_1 <- function(prm) { -1 * sum(dat_v2$weights * apply(dat_v2, 1, function(r) { log(pmax(prob_s(s=r[["s"]], x=as.numeric(r[1:dim_x]), prm), 1e-8)) })) } # Run optimizer (edge) opt_1 <- Rsolnp::solnp( pars = rep(0.01, dim_x+1), fun = wlik_1 ) if (opt_1$convergence!=0) { warning("f_sIx_n: Rsolnp::solnp did not converge") } prm_1 <- opt_1$pars # Filter out observations with s==0 dat_1 <- dat_v2[dat_v2$s!=0,] # Set up weighted likelihood (Normal) wlik_2 <- function(prm) { -1 * sum(dat_1$weights * apply(dat_1, 1, function(r) { log(pmax(dens_s(s=r[["s"]], x=as.numeric(r[c(1:dim_x)]), prm), 1e-8)) })) } # Run optimizer (Normal) opt_2 <- Rsolnp::solnp( pars = c(rep(0.01, dim_x+1), 0.15), fun = wlik_2 ) if (opt_2$convergence!=0) { warning("f_sIx_n: Rsolnp::solnp() did not converge") } prm_2 <- opt_2$pars # Remove large intermediate objects rm(dat_v2,dat_1,opt_1,opt_2) fnc <- function(s, x) { if (s==0) { return(prob_s(s=0, x, prm_1) / 0.01) } else { return(prob_s(s=1, x, prm_1) * dens_s(s, x, prm_2)) } } } if (type=="binning") { # Set up binning density (based on Diaz and Van Der Laan 2011) # prm[1] through prm[k-1] are the hazard components for the bins 1 to k-1 # prm[k] and prm[k+1] are the coefficients for W1 and W2 create_dens <- function(k, dat_v2, remove_dat=F) { # Cut points alphas <- seq(0, 1, length.out=k+1) # Density for a single observation dens_s <- memoise2(function(s, x, prm) { bin <- ifelse(s==1, k, which.min(s>=alphas)-1) hz <- expit( prm[c(1:(ifelse(bin==k,k-1,bin)))] + as.numeric(prm[c(k:(k+length(x)-1))] %*% x) ) p1 <- ifelse(bin==k, 1, hz[bin]) p2 <- ifelse(bin==1, 1, prod(1-hz[1:(bin-1)])) return(k*p1*p2) }) # Set up weighted likelihood wlik <- function(prm) { -1 * sum(dat_v2$weights * log(pmax(apply(dat_v2, 1, function(r) { dens_s(s=r[["s"]], x=as.numeric(r[1:dim_x]), prm) }),1e-8))) } # Run optimizer if(.Platform$OS.type=="unix") { sink("/dev/null") } else { sink("NUL") } opt <- Rsolnp::solnp( pars = rep(0.001,k+dim_x-1), fun = wlik ) sink() if (opt$convergence!=0) { warning("f_sIx_n: Rsolnp::solnp() did not converge") } prm <- opt$pars # Remove large intermediate objects rm(dens_s,opt) if (remove_dat) { rm(dat_v2) } fnc <- function(s, x) { bin <- ifelse(s==1, k, which.min(s>=alphas)-1) hz <- sapply(c(1:(k-1)), function(j) { expit(prm[j] + prm[c(k:(k+length(x)-1))] %*% x) }) p1 <- ifelse(bin==k, 1, hz[bin]) p2 <- ifelse(bin==1, 1, prod(1-hz[1:(bin-1)])) return(k*p1*p2) } } # Select k via cross-validation if (k==0) { # Prep n_folds <- 5 folds <- sample(cut(c(1:n_vacc2), breaks=n_folds, labels=FALSE)) ks <- c(4,8,12,16) # !!!!! Make this an argument best <- list(k=999, max_log_lik=999) # Cross-validation for (k in ks) { sum_log_lik <- 0 for (i in c(1:n_folds)) { dat_train <- dat_v2[which(folds!=i),] dat_test <- dat_v2[which(folds==i),] dens <- create_dens(k, dat_train) sum_log_lik <- sum_log_lik + sum(log(apply(dat_test, 1, function(r) { dens(r[["s"]], as.numeric(r[c(1:dim_x)])) }))) } if (sum_log_lik>best$max_log_lik || best$max_log_lik==999) { best$k <- k best$max_log_lik <- sum_log_lik } } k <- best$k message(paste("Number of bins selected (f_sIx_n):", k)) # !!!!! make this configurable with verbose option } fnc <- create_dens(k, dat_v2, remove_dat=T) } return(memoise2(fnc)) } #' Construct estimator of marginal density of S #' #' @param dat_orig Dataset returned by `generate_data` #' @param f_sIx_n A conditional density estimator returned by #' `construct_f_sIx_n` #' @return Marginal density estimator function #' @noRd construct_f_s_n <- function(dat_v, f_sIx_n) { n_vacc <- attr(dat_v, "n_vacc") dim_x <- attr(dat_v, "dim_x") if (attr(dat_v, "covariates_ph2")) { dat_v2 <- dat_v[dat_v$z==1,] datx_v2 <- dat_v2[, c(1:dim_x), drop=F] memoise2(function(s) { (1/n_vacc) * sum(dat_v2$weights * apply(datx_v2, 1, function(x) { f_sIx_n(s,as.numeric(x)) })) }) } else { datx_v <- dat_v[, c(1:dim_x), drop=F] memoise2(function(s) { (1/n_vacc) * sum(apply(datx_v, 1, function(x) { f_sIx_n(s,as.numeric(x)) })) }) } } #' Construct density ratio estimator g_n #' #' @param f_sIx_n Conditional density estimator returned by construct_f_sIx_n #' @param f_s_n Marginal density estimator returned by construct_f_s_n #' @return Density ratio estimator function #' @noRd construct_g_n <- function(f_sIx_n, f_s_n) { memoise2(function(s,x) { f_sIx_n(s,x) / f_s_n(s) }) } #' Construct Phi_n #' #' @param dat_orig Dataset returned by `generate_data` #' @param dat Subsample of dataset returned by `ss` for which z==1 #' @param type One of c("step", "linear (mid)") #' @return IPS-weighted CDF estimator function #' @noRd construct_Phi_n <- function (dat_v2, dat, type="linear (mid)") { # !!!!! type currently ignored n_vacc <- attr(dat_v2, "n_vacc") fnc <- memoise2(function(x) { (1/n_vacc) * sum(dat_v2$weights*In(dat_v2$s<=x)) }) return(memoise2(fnc)) } #' Construct g-computation estimator function of theta_0 #' #' @param dat_orig Dataset returned by `generate_data` #' @param Q_n Conditional survival function estimator returned by #' `construct_Q_n` #' @return G-computation estimator of theta_0 #' @noRd construct_r_tilde_Mn <- function(dat_v, Q_n, t_0) { n_vacc <- attr(dat_v, "n_vacc") dim_x <- attr(dat_v, "dim_x") if (attr(dat_v, "covariates_ph2")) { dat_v2 <- dat_v[dat_v$z==1,] datx_v2 <- dat_v2[, c(1:dim_x), drop=F] memoise2(function(s) { 1 - (1/n_vacc) * sum(dat_v2$weights * apply(datx_v2, 1, function(x) { Q_n(t_0, as.numeric(x), s) })) }) } else { datx_v <- dat_v[, c(1:dim_x), drop=F] memoise2(function(s) { 1 - (1/n_vacc) * sum(apply(datx_v, 1, function(x) { Q_n(t_0, as.numeric(x), s) })) }) } } #' Construct nuisance estimator of conditional density f(Y,Delta|X,S) #' #' @noRd construct_f_n_srv <- function(Q_n, Qc_n, grid) { # Helper function to calculate derivatives construct_surv_deriv <- function(Q) { max_index <- length(grid$y) fnc <- function(t, x, s) { t_index <- which.min(abs(grid$y-t)) if (t_index==1) { t1 <- 0 t2 <- grid$y[2] } else if (t_index==max_index) { t1 <- grid$y[round(max_index-1)] t2 <- grid$y[max_index] } else { t1 <- grid$y[round(t_index-1)] t2 <- grid$y[round(t_index+1)] } return((Q(t2,x,s)-Q(t1,x,s))/(t2-t1)) } return(memoise2(fnc)) } # Calculate derivative estimators Q_n_deriv <- construct_surv_deriv(Q_n) Qc_n_deriv <- construct_surv_deriv(Qc_n) fnc <- function(y, delta, x, s) { if (delta==1) { return(-1*Qc_n(y,x,s)*Q_n_deriv(y,x,s)) } else { return(-1*Q_n(y,x,s)*Qc_n_deriv(y,x,s)) } } return(memoise2(fnc)) } #' Construct q_n nuisance estimator function #' #' @noRd construct_q_n <- function(type="standard", dat_v2, omega_n, g_n, r_tilde_Mn, f_n_srv) { if (type=="standard") { # !!!!! Can this function be used elsewhere? q_n_star_inner <- memoise2(function(x,y,delta,s) { omega_n(x,s,y,delta)/g_n(s,x)+r_tilde_Mn(s) }) # q_n_star <- memoise2(function(y,delta,x,s,u) { q_n_star <- function(y,delta,x,s,u) { if (s>u) { return(0) } else { return(q_n_star_inner(x,y,delta,s)) } # }) } # Helper functions # !!!!! Can these vectors/functions be used elsewhere? f_n_srv_s <- memoise2(function(y,delta,x) { sapply(dat_v2$s, function(s) { f_n_srv(y,delta,x,s) }) }) q_n_star_s <- memoise2(function(y,delta,x,u) { sapply(dat_v2$s, function(s) { q_n_star(y,delta,x,s,u) }) }) g_n_s <- memoise2(function(x) { sapply(dat_v2$s, function(s) { g_n(s,x) }) }) fnc <- function(x,y,delta,u) { f_n_srv_s <- f_n_srv_s(y,delta,x) q_n_star_s <- q_n_star_s(y,delta,x,u) g_n_s <- g_n_s(x) denom <- sum(dat_v2$weights*f_n_srv_s*g_n_s) if (denom==0) { return (0) } else { num <- sum(dat_v2$weights*q_n_star_s*f_n_srv_s*g_n_s) return(num/denom) } } return(memoise2(fnc)) } if (type=="zero") { return(function(x, y, delta, u) { 0 }) } } #' Construct estimator of nuisance g_sn #' #' @noRd construct_g_sn <- function(dat_v2, f_n_srv, g_n, p_n) { n_vacc <- attr(dat_v2, "n_vacc") return(memoise2(function(x, y, delta) { num <- f_n_srv(y, delta, x, 0) * g_n(s=0,x) * (1-p_n) den <- (1/n_vacc) * sum(dat_v2$weights * sapply(dat_v2$s, function(s) { f_n_srv(y,delta,x,s) * g_n(s,x) })) if (den==0) { return(0) } else { return(num/den) } })) } #' Construct gamma_n nuisance estimator function #' #' @param dat_orig Dataset returned by `generate_data` #' @param dat Subsample of dataset returned by `ss` for which z==1 #' @param vals List of values to pre-compute function on #' @param type Type of regression; one of c("cubic", "kernel", "kernel2") #' @param omega_n A nuisance influence function returned by `construct_omega_n` #' @param f_sIx_n A conditional density estimator returned by #' `construct_f_sIx_n` #' @param f_sIx_n A conditional density estimator returned by #' `construct_f_sIx_n` among the observations for which z==1 #' @return gamma_n nuisance estimator function #' @noRd construct_gamma_n <- function(dat_v, type="Super Learner", omega_n, grid) { dim_x <- attr(dat_v, "dim_x") dat_v2 <- dat_v[dat_v$z==1,] datx_v <- dat_v[, c(1:dim_x), drop=F] class(datx_v) <- "data.frame" # Construct pseudo-outcomes omega_n_d <- apply(dat_v2, 1, function(r) { omega_n(as.numeric(r[1:dim_x]), r[["s"]], r[["y"]], r[["delta"]]) }) dat_v2$po <- (dat_v2$weights*as.numeric(omega_n_d))^2 # Filter out infinite values if (sum(!is.finite(dat_v2$po))!=0) { dat_v2 <- dat_v2[which(is.finite(dat_v2$po)),] warning(paste("gamma_n:", sum(!is.finite(dat_v2$po)), "non-finite pseudo-outcome values")) } # Setup if (attr(dat_v, "covariates_ph2")) { datx_v2 <- dat_v2[, c(1:dim_x), drop=F] class(datx_v2) <- "data.frame" x_distinct <- dplyr::distinct(datx_v2) } else { x_distinct <- dplyr::distinct(datx_v) } x_distinct <- cbind("x_index"=c(1:nrow(x_distinct)), x_distinct) newX <- expand.grid(x_index=x_distinct$x_index, s=grid$s) newX <- dplyr::inner_join(x_distinct, newX, by="x_index") newX$x_index <- NULL # Run regression if (type=="Super Learner") { # Fit SuperLearner regression do.call("library", list("SuperLearner")) # SL.library <- c("SL.mean", "SL.gam", "SL.ranger", "SL.earth", "SL.loess", # "SL.nnet", "SL.ksvm", "SL.rpartPrune", "SL.svm") SL.library <- c("SL.mean", "SL.mean", "SL.gam", "SL.gam", "SL.ranger") # Changed on 2024-02-13; SL.mean written twice to avoid SuperLearner bug model_sl <- suppressWarnings(SuperLearner::SuperLearner( Y = dat_v2$po, X = dat_v2[,c(1:dim_x,which(names(dat_v2)=="s"))], newX = newX, family = "gaussian", SL.library = SL.library, verbose = F )) pred <- as.numeric(model_sl$SL.predict) if (sum(pred<0)!=0) { warning(paste("gamma_n:", sum(pred<0), "negative predicted values.")) } # Construct regression function reg <- function(x,s) { pred[find_index(c(x,s), newX)] } } # Remove large intermediate objects rm(dat_v,dat_v2,datx_v,omega_n,model_sl) return(memoise2(reg)) } #' Construct estimator of g_z0(x,s) = P(Z=1|X=x,S=s) #' #' @noRd construct_g_zn <- function(dat_v, type="Super Learner", f_sIx_n, f_sIx_z1_n) { # Prevents CRAN Note if (F) { x <- ranger::ranger x <- gam::gam } # Set library if (type=="Super Learner") { do.call("library", list("SuperLearner")) # SL.library <- c("SL.mean", "SL.gam", "SL.ranger", "SL.earth", "SL.nnet", # "SL.glmnet") # SL.library <- c("SL.mean", "SL.gam", "SL.ranger", "SL.nnet", # "SL.glmnet") SL.library <- c("SL.mean", "SL.mean", "SL.gam", "SL.gam", "SL.ranger") # Changed 2024-02-13; SL.mean written twice to avoid SuperLearner bug } else if (type=="logistic") { SL.library <- c("SL.glm") } # Create data objects dim_x <- attr(dat_v, "dim_x") dat_v2 <- dat_v[dat_v$z==1,] datx_v <- dat_v[, c(1:dim_x), drop=F] datx_v2 <- dat_v2[, c(1:dim_x), drop=F] class(datx_v) <- "data.frame" class(datx_v2) <- "data.frame" # Fit SuperLearner regression if (attr(dat_v, "covariates_ph2")) { newX <- dplyr::distinct(datx_v2) model_sl <- suppressWarnings(SuperLearner::SuperLearner( Y = dat_v2$z, X = datx_v2, newX = newX, family = "binomial", SL.library = SL.library, verbose = F )) } else { newX <- dplyr::distinct(datx_v) model_sl <- suppressWarnings(SuperLearner::SuperLearner( Y = dat_v$z, X = datx_v, newX = newX, family = "binomial", SL.library = SL.library, verbose = F )) } pred <- as.numeric(model_sl$SL.predict) # Construct regression function reg <- function(x) { pred[find_index(x, newX)] } # Remove large intermediate objects rm(dat_v,datx_v,model_sl) return(memoise2(function(x,s) { (f_sIx_z1_n(s,x)/f_sIx_n(s,x))*reg(x) })) } #' Construct derivative estimator r_Mn'_n #' #' #' @param r_Mn An estimator of r_M0 #' @param type One of c("m-spline", "linear", "line") #' @param dir One of c("decr", "incr") #' @param grid TO DO #' @noRd construct_deriv_r_Mn <- function(type="m-spline", r_Mn, dir, grid) { if (type=="line") { fnc <- function(s) { r_Mn(1)-r_Mn(0) } } else { if (r_Mn(0)==r_Mn(1)) { fnc <- function(s) { 0 } warning("Estimated function is flat; variance estimation not possible.") } # Estimate entire function on grid r_Mns <- sapply(grid$s, r_Mn) # Compute set of midpoints of jump points (plus endpoints) points_x <- grid$s[1] points_y <- r_Mns[1] for (i in 2:length(grid$s)) { if (r_Mns[i]-r_Mns[round(i-1)]!=0) { points_x <- c(points_x, (grid$s[i]+grid$s[round(i-1)])/2) points_y <- c(points_y, mean(c(r_Mns[i],r_Mns[round(i-1)]))) } } points_x <- c(points_x, grid$s[length(grid$s)]) points_y <- c(points_y, r_Mns[length(grid$s)]) if (type=="linear") { fnc_pre <- stats::approxfun(x=points_x, y=points_y, method="linear", rule=2) } if (type=="m-spline") { fnc_pre <- stats::splinefun(x=points_x, y=points_y, method="monoH.FC") } # Construct numerical derivative fnc <- function(s) { width <- 0.1 # !!!!! Changed from 0.2 x1 <- s - width/2 x2 <- s + width/2 if (x1<0) { x2<-width; x1<-0; } if (x2>1) { x1<-1-width; x2<-1; } if (dir=="decr") { return(min((fnc_pre(x2)-fnc_pre(x1))/width,0)) } else { return(max((fnc_pre(x2)-fnc_pre(x1))/width,0)) } } } return(fnc) } #' Construct tau_n Chernoff scale factor function #' #' @param deriv_r_Mn A derivative estimator returned by `construct_deriv_r_Mn` #' @param gamma_n Nuisance function estimator returned by `construct_gamma_n` #' @param f_s_n Density estimator returned by `construct_f_s_n` #' @return Chernoff scale factor estimator function #' @noRd construct_tau_n <- function(dat_v, deriv_r_Mn, gamma_n, f_sIx_n, g_zn) { n_vacc <- attr(dat_v, "n_vacc") dim_x <- attr(dat_v, "dim_x") dat_v2 <- dat_v[dat_v$z==1,] if (attr(dat_v, "covariates_ph2")) { dat_apply <- dat_v2 } else { dat_apply <- dat_v } return(function(u) { abs(4*deriv_r_Mn(u) * (1/n_vacc) * sum(apply(dat_apply, 1, function(r) { x <- as.numeric(r[1:dim_x]) return((gamma_n(x,u)*g_zn(x,u))/f_sIx_n(u,x)) })))^(1/3) }) } #' Construct nuisance estimator eta*_n #' #' @param Q_n Conditional survival function estimator returned by construct_Q_n #' @param vals List of values to pre-compute function on; passed to #' construct_superfunc() #' @return Estimator function of nuisance eta*_0 #' @noRd construct_etastar_n <- function(Q_n, t_0, grid) { int_values <- memoise2(function(x) { sapply(grid$s, function(s) { Q_n(t_0, x, s) }) }) fnc <- function(u,x) { indices <- which(grid$s<=u) # s_seq <- vals$s[indices] if (u==0 || length(indices)==0) { return(0) } else { # integral <- u * mean(sapply(s_seq, function(s) { Q_n(t_0, x, s) })) integral <- u * mean(int_values(x)[indices]) return(u-integral) } } return(memoise2(fnc)) } #' Construct q_tilde_n nuisance estimator function #' #' @param x x #' @return q_tilde_n nuisance estimator function #' @noRd construct_q_tilde_n <- function(type="new", f_n_srv, f_sIx_n, omega_n) { if (type=="new") { # !!!!! TO DO # seq_01 <- round(seq(C$appx$s,1,C$appx$s),-log10(C$appx$s)) # # fnc <- function(x, y, delta, u) { # # denom <- C$appx$s * sum(sapply(seq_01, function(s) { # f_n_srv(y, delta, x, s) * f_sIx_n(s,x) # })) # # if (denom==0) { # return (0) # } else { # if (u==0) { # return(0) # } else { # seq_0u <- round(seq(C$appx$s,u,C$appx$s),-log10(C$appx$s)) # num <- C$appx$s * sum(sapply(seq_0u, function(s) { # omega_n(x,s,y,delta) * f_n_srv(y, delta, x, s) # })) # return(num/denom) # } # } # # } } if (type=="zero") { fnc <- function(x, y, delta, u) { 0 } return(fnc) # !!!!! TEMP } return(memoise2(fnc)) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/nuisance_estimators.R
#' Construct Gamma_os_n primitive one-step estimator (based on EIF) #' #' @noRd construct_Gamma_os_n <- function(dat_v, omega_n, g_n, q_n, r_tilde_Mn) { dat_v2 <- dat_v[dat_v$z==1,] n_vacc <- attr(dat_v, "n_vacc") dim_x <- attr(dat_v, "dim_x") piece_1 <- as.numeric(apply(dat_v2, 1, function(r) { x <- as.numeric(r[1:dim_x]) s <- r[["s"]] y <- r[["y"]] delta <- r[["delta"]] g_n_val <- g_n(s,x) if (is.nan(g_n_val)) { stop(paste0("One or more g_n values were NAN; density might be zero. Try ", "using a density estimator that guarantees positive density ", "estimates.")) } return((omega_n(x,s,y,delta)/g_n_val)+r_tilde_Mn(s)) })) piece_2 <- 1 - dat_v$weights # Remove large intermediate objects rm(omega_n,g_n,r_tilde_Mn) fnc <- function(u) { q_n_do <- as.numeric(apply(dat_v, 1, function(r) { q_n(as.numeric(r[1:dim_x]), r[["y"]], r[["delta"]], u) })) return((1/n_vacc) * sum(dat_v2$weights * (In(dat_v2$s<=u)*piece_1)) + (1/n_vacc) * sum(piece_2*q_n_do)) } return(memoise2(fnc)) } #' Compute one-step estimator of counterfactual risk at S=0 #' #' @param dat Subsample of dataset returned by ss() for which z==1 #' @param g_sn Propensity score estimator returned by construct_g_sn() #' @param Q_n Conditional survival function estimator returned by construct_Q_n #' @param omega_n A nuisance influence function returned by construct_omega_n() #' @return Value of one-step estimator #' @noRd r_Mn_edge <- function(dat_v_rd, g_sn, g_n, p_n, Q_n, omega_n, t_0) { n_vacc <- attr(dat_v_rd, "n_vacc") dim_x <- attr(dat_v_rd, "dim_x") v <- (1/n_vacc) * sum(apply(dat_v_rd, 1, function(r) { y <- r[["y"]] delta <- r[["delta"]] z <- r[["z"]] x <- as.numeric(r[1:dim_x]) if (z==0) { s <- 0 pi_ <- 1 } else { s <- r[["s"]] pi_ <- 1/r[["weights"]] } return( ((z*In(s==0)+g_sn(x,y,delta)*(pi_-z))*omega_n(x,s=0,y,delta)) / (pi_*(1-p_n)*g_n(s=0,x)) - Q_n(t_0,x,s=0) ) })) return(1+v) } #' Compute one-step estimator of overall risk (vaccine group) #' #' @param TODO TO DO #' @return Value of one-step estimator #' @noRd risk_overall_np_v <- function(dat_v_rd, g_n, Q_n, omega_n, f_n_srv, q_tilde_n, t_0) { # !!!!! Port to est_overall n_vacc <- attr(dat_v_rd, "n_vacc") dim_x <- attr(dat_v_rd, "dim_x") v <- (1/n_vacc) * sum(apply(dat_v_rd, 1, function(r) { y <- r[["y"]] delta <- r[["delta"]] z <- r[["z"]] x <- as.numeric(r[1:dim_x]) if (z==0) { s <- 0 pi_ <- 1 } else { s <- r[["s"]] pi_ <- 1/r[["weights"]] } val <- (z/pi_)*(omega_n(x,s,y,delta)-Q_n(t_0,x,s)) + (1-z/pi_)*q_tilde_n(x,y,delta) return(val) })) return(1+v) } #' Compute one-step estimator of overall risk (placebo group) #' #' @param TODO TO DO #' @return Value of one-step estimator #' @noRd risk_overall_np_p <- function(dat_p_rd, Q_noS_n, omega_noS_n, t_0) { # !!!!! Port to est_overall n_plac <- attr(dat_p_rd, "n_plac") dim_x <- attr(dat_p_rd, "dim_x") v <- (1/n_plac) * sum(apply(dat_p_rd, 1, function(r) { x <- as.numeric(r[1:dim_x]) omega_noS_n(x,r[["y"]],r[["delta"]])-Q_noS_n(t_0,x) })) return(1+v) } #' Compute one-step estimator of overall risk (placebo group) #' #' @param TODO TO DO #' @return Value of one-step estimator #' @noRd risk_overall_np_v_v2 <- function(dat_v_rd, Q_noS_n_v, omega_noS_n_v, t_0) { # !!!!! Port to est_overall n_vacc <- attr(dat_v_rd, "n_vacc") dim_x <- attr(dat_v_rd, "dim_x") v <- (1/n_vacc) * sum(apply(dat_v_rd, 1, function(r) { x <- as.numeric(r[1:dim_x]) omega_noS_n_v(x,r[["y"]],r[["delta"]])-Q_noS_n_v(t_0,x) })) return(1+v) } #' Construct Theta_os_n primitive one-step estimator #' #' @param dat Subsample of dataset returned by ss() for which z==1 #' @param vals List of values to pre-compute function on; passed to #' construct_superfunc() #' @param omega_n A nuisance influence function returned by construct_omega_n() #' @param f_sIx_n Conditional density estimator returned by construct_f_sIx_n #' @param etastar_n A nuisance estimator returned by construct_etastar_n() #' @return Gamma_os_n estimator #' @note This is a generalization of the one-step estimator from Westling & #' Carone 2020 #' @noRd construct_Theta_os_n <- function(dat_v, omega_n, f_sIx_n, q_tilde_n, etastar_n) { dat_v2 <- dat_v[dat_v$z==1,] n_vacc <- attr(dat_v, "n_vacc") dim_x <- attr(dat_v, "dim_x") piece_1 <- as.numeric(apply(dat_v2, 1, function(r) { x <- as.numeric(r[1:dim_x]) s <- r[["s"]] y <- r[["y"]] delta <- r[["delta"]] weight <- r[["weights"]] f_sIx_n_val <- f_sIx_n(s,x) if (is.nan(f_sIx_n_val)) { stop(paste0("One or more f_sIx_n_val values were NAN; density might be z", "ero. Try using a density estimator that guarantees positive", " density estimates.")) } return((weight*omega_n(x,s,y,delta)) / f_sIx_n_val) })) # Remove large intermediate objects rm(omega_n,f_sIx_n) fnc <- function(u) { (1/n_vacc) * sum(piece_1*In(dat_v2$s<=u)) + (1/n_vacc) * sum(as.numeric(apply(dat_v, 1, function(r) { weights <- r[["weights"]] x <- as.numeric(r[1:dim_x]) y <- r[["y"]] delta <- r[["delta"]] return((1-weights) * q_tilde_n(x,y,delta,u) + etastar_n(u,x)) }))) } return(memoise2(fnc)) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/one_step_estimators.R
#' Set parameters controlling Cox model estimation of controlled effect curves #' #' @description This should be used in conjunction with \code{\link{est_ce}} to #' set parameters controlling Cox model estimation of controlled effect #' curves; see examples. #' @param spline_df An integer; if the marker is modeled flexibly within the Cox #' model linear predictor as a natural cubic spline, this option controls #' the degrees of freedom in the spline; knots are chosen to be equally #' spaced across the range of the marker. #' @param spline_knots A numeric vector; as an alternative to specifying #' \code{spline_df}, the exact locations of the knots in the spline #' (including boundary knots) can be specified with this option. #' @param edge_ind Boolean. If TRUE, an indicator variable corresponding to the #' lower limit of the marker will be included in the Cox model linear #' predictor. #' @return A list of options. #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_cox <- est_ce( #' dat = dat, #' type = "Cox", #' t_0 = 578, #' params_cox = params_ce_cox(spline_df=4) #' ) #' } #' @export params_ce_cox <- function(spline_df=NA, spline_knots=NA, edge_ind=FALSE) { return(list(spline_df=spline_df, spline_knots=spline_knots, edge_ind=edge_ind)) } #' Set parameters controlling nonparametric estimation of controlled effect #' curves #' #' @description This should be used in conjunction with \code{\link{est_ce}} to #' set parameters controlling nonparametric estimation of controlled effect #' curves; see examples. #' @param dir One of c("decr", "incr"); controls the direction of monotonicity. #' If dir="decr", it is assumed that CR decreases as a function of the #' marker. If dir="incr", it is assumed that CR increases as a function of #' the marker. #' @param edge_corr Boolean. If TRUE, the "edge correction" is performed to #' adjust for bias near the marker lower limit (see references). It is #' recommended that the edge correction is only performed if there are at #' least (roughly) 10 events corresponding to the marker lower limit. #' @param grid_size A list with keys \code{y}, \code{s}, and \code{x}; controls #' the rounding of data values. Decreasing the grid size values results in #' shorter computation times, and increasing the values results in more #' precise estimates. If grid_size$s=101, this means that a grid of 101 #' equally-spaced points (defining 100 intervals) will be created from #' min(S) to max(S), and each S value will be rounded to the nearest grid #' point. For grid_size$y, a grid will be created from 0 to t_0, and then #' extended to max(Y). For grid_size$x, a separate grid is created for each #' covariate column (binary/categorical covariates are ignored). #' @param surv_type One of c("Cox", "survSL", "survML-G", "survML-L"); controls #' the method to use to estimate the conditional survival and conditional #' censoring functions. If type="Cox", a survival function based on a Cox #' proportional hazard model will be used. If type="survSL", the Super #' Learner method of Westling 2023 is used. If type="survML-G", the global #' survival stacking method of Wolock 2022 is used. If type="survML-L", the #' local survival stacking method of Polley 2011 is used. #' @param density_type One of c("binning", "parametric"); controls the method to #' use to estimate the density ratio f(S|X)/f(S). #' @param density_bins An integer; if density_type="binning", the number of bins #' to use. If density_bins=0, the number of bins will be selected via #' cross-validation. #' @param deriv_type One of c("m-spline", "linear"); controls the method to use #' to estimate the derivative of the CR curve. If deriv_type="linear", a #' linear spline is constructed based on the midpoints of the jump points of #' the estimated function (plus the estimated function evaluated at the #' endpoints), which is then numerically differentiated. #' deriv_type="m-spline" is similar to deriv_type="linear" but smooths the #' set of points (using the method of Fritsch and Carlson 1980) before #' differentiating. #' @param convex_type One of c("GCM", "CLS"). Whether the greatest convex #' minorant ("GCM") or convex least squares ("CLS") projection should be #' used in the smoothing of the primitive estimator Gamma_n. #' convex_type="CLS" is experimental and should be used with caution. #' @return A list of options. #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_np <- est_ce( #' dat = dat, #' type = "NP", #' t_0 = 578, #' params_np = params_ce_np(edge_corr=TRUE, surv_type="survML-L") #' ) #' } #' @export params_ce_np <- function( dir = "decr", edge_corr = FALSE, grid_size = list(y=101,s=101,x=5), surv_type = "survML-G", density_type = "binning", density_bins = 15, deriv_type = "m-spline", convex_type = "GCM" ) { return(list(dir=dir, edge_corr=edge_corr, grid_size=grid_size, surv_type=surv_type, density_type=density_type, density_bins=density_bins, deriv_type=deriv_type, convex_type=convex_type)) } #' Set parameters controlling nonparametric estimation of mediation effects #' #' @description This should be used in conjunction with \code{\link{est_med}} to #' set parameters controlling nonparametric estimation of mediation effects; #' see examples. #' @param grid_size A list with keys \code{y}, \code{s}, and \code{x}; controls #' the rounding of data values. Decreasing the grid size values results in #' shorter computation times, and increasing the values results in more #' precise estimates. If grid_size$s=101, this means that a grid of 101 #' equally-spaced points (defining 100 intervals) will be created from #' min(S) to max(S), and each S value will be rounded to the nearest grid #' point. For grid_size$y, a grid will be created from 0 to t_0, and then #' extended to max(Y). For grid_size$x, a separate grid is created for each #' covariate column (binary/categorical covariates are ignored). #' @param surv_type One of c("Cox", "survSL", "survML-G", "survML-L"); controls #' the method to use to estimate the conditional survival and conditional #' censoring functions. If type="Cox", a survival function based on a Cox #' proportional hazard model will be used. If type="survSL", the Super #' Learner method of Westling 2023 is used. If type="survML-G", the global #' survival stacking method of Wolock 2022 is used. If type="survML-L", the #' local survival stacking method of Polley 2011 is used. #' @param density_type One of c("binning", "parametric"); controls the method to #' use to estimate the density ratio f(S|X)/f(S). #' @param density_bins An integer; if density_type="binning", the number of bins #' to use. If density_bins=0, the number of bins will be selected via #' cross-validation. #' @return A list of options. #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_med <- est_med( #' dat = dat, #' type = "NP", #' t_0 = 578, #' params_np = params_med_np(surv_type="survML-L") #' ) #' } #' @export params_med_np <- function( grid_size = list(y=101,s=101,x=5), surv_type = "survML-G", density_type = "binning", density_bins = 15 ) { return(list(grid_size=grid_size, surv_type=surv_type, density_type=density_type, density_bins=density_bins)) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/params.R
#' Plotting controlled effect curves #' #' @description Plot CR and/or CVE curves #' @param ... One or more objects of class \code{"vaccine_est"} returned by #' \code{\link{est_ce}}. #' @param which One of c("CR", "CVE"); controls whether to plot CR curves or CVE #' curves. #' @param density_type One of c("none", "kde", "kde edge"). #' Controls the type of estimator used for the background marker density #' plot. For "none", no density plot is displayed. For "kde", a weighted #' kernel density estimator is used. For "kde edge", a modified version of #' "kde" is used that allows for a possible point mass at the left edge of #' the marker distribution. #' @param dat The data object originally passed into \code{\link{est_ce}}. It is #' only necessary to pass this in if \code{density_type} is not set to #' "none". #' @param zoom_x Either one of c("zoom in", "zoom out") or a vector of #' length 2. Controls the zooming on the X-axis. The default "zoom in" will #' set the zoom limits to the plot estimates. Choosing "zoom out" will set #' the zoom limits to show the entire distribution of the marker. Entering a #' vector of length 2 will set the left and right zoom limits explicitly. #' @param zoom_y Either "zoom out" or a vector of length 2. Controls the zooming #' on the Y-axis. The default "zoom out" will show the entire vertical range #' of the estimates. Entering a vector of length 2 will set the lower and #' upper zoom limits explicitly. #' @return A plot of CR/CVE estimates #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_cox <- est_ce(dat=dat, type="Cox", t_0=578) #' ests_np <- est_ce(dat=dat, type="NP", t_0=578) #' plot_ce(ests_cox, ests_np) #' } #' @export plot_ce <- function(..., which="CR", density_type="none", dat=NA, zoom_x="zoom in", zoom_y="zoom out") { # !!!!! Check dat # !!!!! Move all error handling into a function # Error handling if (!(which %in% c("CR", "CVE"))) { stop("`which` must equal one of c('CR','CVE').") } if (length(list(...))==0) { stop(paste0("One or more objects of class 'vaccine_est' must be passed int", "o `plot_ce`.")) } if (density_type!="none" && missing(dat)) { stop("If `density_type` is not set to 'none', `dat` must also be provided.") } if (!(length(zoom_x) %in% c(1,2)) || (length(zoom_x)==2 && !methods::is(zoom_x, "numeric")) || (length(zoom_x)==1 && !(zoom_x %in% c("zoom out", "zoom in")))) { stop(paste0("`zoom_x` must equal either 'zoom in' or 'zoom out', or be a n", "umeric vector of length 2.")) } if (length(zoom_x)==1 && zoom_x=="zoom out" && missing(dat)) { stop("If `zoom_x` is set to 'zoom out', `dat` must be provided as well.") } if (!(length(zoom_y) %in% c(1,2)) || (length(zoom_y)==2 && !methods::is(zoom_y, "numeric")) || (length(zoom_y)==1 && zoom_y!="zoom out")) { stop(paste0("`zoom_y` must equal 'zoom out' or be a numeric vector ", "of length 2.")) } # !!!!! Add to examples: # plot_ce(ests_cox, ests_np, density=list(s=dat_v$s, weights=dat_v$weights)) # To prevent R CMD CHECK notes x <- y <- ci_lower <- ci_upper <- curve <- ymin <- ymax <- NULL rm(x, y, ci_lower, ci_upper, curve, ymin, ymax) df_plot <- as_table(..., which=which) # Set X-axis zoom values z_x <- rep(NA,2) if (length(zoom_x)==2) { z_x <- zoom_x } else { if (zoom_x=="zoom in") { z_x[1] <- min(df_plot$x) z_x[2] <- max(df_plot$x) } else if (zoom_x=="zoom out") { dat_v <- dat[dat$a==1,] z_x[1] <- min(dat_v$s, na.rm=T) z_x[2] <- max(dat_v$s, na.rm=T) } # Add 5% padding to zoom z_x[1] <- z_x[1] - 0.05*(z_x[2]-z_x[1]) z_x[2] <- z_x[2] + 0.05*(z_x[2]-z_x[1]) } # Set Y-axis zoom values z_y <- rep(NA,2) if (length(zoom_y)==2) { z_y <- zoom_y } else if (zoom_y=="zoom out") { zz <- dplyr::filter(df_plot, x>=z_x[1] & x<=z_x[2]) z_y[1] <- ifelse(which=="CVE", min(zz$ci_lower, na.rm=T), 0) z_y[2] <- max(zz$ci_upper, na.rm=T) # Add 5% padding to zoom z_y[1] <- z_y[1] - 0.05*(z_y[2]-z_y[1]) z_y[2] <- z_y[2] + 0.05*(z_y[2]-z_y[1]) } # Construct KDE dataframe if (density_type!="none") { dat_v <- dat[dat$a==1,] min_s <- min(dat_v$s, na.rm=T) p_edge <- mean(dat_v$s==min_s, na.rm=T) # !!!!! Make this weighted if (p_edge<0.03 & density_type=="kde edge") { density_type <- "kde" } dens_height <- 0.6 * (z_y[2]-z_y[1]) if (density_type=="kde") { df_dens <- data.frame( s = dat_v$s[!is.na(dat_v$s)], weights = dat_v$weights[!is.na(dat_v$s)] ) df_dens$weights <- df_dens$weights / sum(df_dens$weights) dens <- suppressWarnings(stats::density( x = df_dens$s, bw = "ucv", weights = df_dens$weights )) kde_data <- data.frame( x = dens$x, ymin = z_y[1], ymax = dens_height * (dens$y/max(dens$y)) + z_y[1] ) } else { df_dens <- data.frame( s = dat_v$s[!is.na(dat_v$s) & dat_v$s!=min_s], weights = dat_v$weights[!is.na(dat_v$s) & dat_v$s!=min_s] ) df_dens$weights <- df_dens$weights / sum(df_dens$weights) dens <- suppressWarnings(stats::density( x = df_dens$s, bw = "ucv", weights = df_dens$weights )) dens$y <- dens$y * (1-p_edge) plot_width <- z_x[2]-z_x[1] rect_x <- c(min_s-0.025*plot_width, min_s+0.025*plot_width) rect_y <- p_edge / (rect_x[2]-rect_x[1]) inds_to_remove <- dens$x>rect_x[2] dens$x <- dens$x[inds_to_remove] dens$y <- dens$y[inds_to_remove] dens$x[length(dens$x)+1] <- rect_x[1] dens$y[length(dens$y)+1] <- rect_y dens$x[length(dens$x)+1] <- rect_x[2] dens$y[length(dens$y)+1] <- rect_y dens$x[length(dens$x)+1] <- rect_x[2] + plot_width/10^5 dens$y[length(dens$y)+1] <- z_y[1] kde_data <- data.frame( x = dens$x, ymin = z_y[1], ymax = dens_height * (dens$y/max(dens$y)) + z_y[1] ) } } # Set plot labels if (which=="CR") { labs <- list(title="Controlled Risk", y="Risk") } else { labs <- list(title="Controlled Vaccine Efficacy", y="CVE") } # Set up ggplot2 object plot <- ggplot2::ggplot( df_plot, ggplot2::aes(x=x, y=y, color=curve, fill=curve) ) + ggplot2::coord_cartesian(xlim=z_x, ylim=z_y, expand=F) # Plot background KDE if (density_type!="none") { plot <- plot + ggplot2::geom_ribbon( ggplot2::aes(x=x, ymin=ymin, ymax=ymax), data = kde_data, inherit.aes = F, color = "white", fill = "orange", # "forestgreen" alpha = 0.3 ) } # Primary plot plot <- plot + ggplot2::geom_line() + ggplot2::geom_ribbon(ggplot2::aes(ymin=ci_lower, ymax=ci_upper), # color="darkorchid3", fill="darkorchid3" alpha = 0.1, linetype = "dotted") + ggplot2::labs(title=labs$title, x="S", y=labs$y, color="", fill="") + ggplot2::theme( legend.position = "bottom", panel.background = ggplot2::element_blank(), panel.border = ggplot2::element_rect(color="#bbbbbb", fill=NA) ) # Implement these eventually curve_colors <- c("darkgrey", "darkorchid3", "firebrick3", "deepskyblue3", "darkgreen", "darkorange") # curve_colors <- c("darkgreen", "darkorange") return(plot) } #' Trim data for plotting/reporting #' #' @description Removes a subset of estimates returned by \code{\link{est_ce}} #' @param ests An object of class \code{"vaccine_est"} returned by #' \code{\link{est_ce}}. #' @param dat The data object originally passed into \code{\link{est_ce}}. #' @param quantiles A vector of length 2 representing the quantiles of the #' marker distribution at which to trim the data; if, for example, #' \code{quantiles=c(0.1,0.9)} is specified, values outside the 10% and 90% #' (weighted) quantiles of the marker distribution will be trimmed. #' @return A modified copy of \code{ests} with the data trimmed. #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_cox <- est_ce(dat=dat, type="Cox", t_0=578) #' ests_cox <- trim(ests_cox, dat=dat, quantiles=c(0.1,0.9)) #' plot_ce(ests_cox, density_type="kde", dat=dat) #' } #' @export trim <- function(ests, dat, quantiles) { dat_v <- dat[dat$a==1,] cutoffs <- stats::quantile(dat_v$s, na.rm=T, probs=quantiles) # !!!!! Make this weighted quantile for (i in c(1:length(ests))) { if (names(ests)[i] %in% c("cr", "cve")) { inds_to_keep <- which(ests[[i]]$s>=cutoffs[[1]] & ests[[i]]$s<=cutoffs[[2]]) for (v in c("s", "est", "se", "ci_lower", "ci_upper")) { ests[[i]][[v]] <- ests[[i]][[v]][inds_to_keep] } } } return(ests) } #' Create table of estimates #' #' @description Format estimates returned by \code{\link{est_ce}} as a table #' @param ... One or more objects of class \code{"vaccine_est"} returned by #' \code{\link{est_ce}}. #' @param which One of c("CR", "CVE"); controls whether the table contains CR or #' CVE values. #' @return A table of CR or CVE values #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' \donttest{ #' ests_cox <- est_ce(dat=dat, type="Cox", t_0=578) #' ests_np <- est_ce(dat=dat, type="NP", t_0=578) #' ests_table <- as_table(ests_cox, ests_np) #' head(ests_table) #' } #' @export as_table <- function(..., which="CR") { # !!!!! Move all error handling into a function df_ests <- data.frame( x = double(), y = double(), ci_lower = double(), ci_upper = double(), curve = character() ) labels <- sapply(substitute(list(...))[-1], deparse) counter <- 1 for (obj in list(...)) { if (!methods::is(obj, "vaccine_est")) { stop(paste0("One or more of the objects passed into `plot_ce` is not of ", "of class 'vaccine_est'.")) } if (which=="CR") { if (methods::is(obj$cr, "NULL")) { stop(paste0("CR estimates not present in one or more `vaccine_est` obj", "ects; try rerunning `est_ce` with cr=TRUE.")) } else { df_add <- data.frame( x = obj$cr$s, y = obj$cr$est, ci_lower = obj$cr$ci_lower, ci_upper = obj$cr$ci_upper, curve = labels[counter] ) } } else if (which=="CVE") { if (methods::is(obj$cve, "NULL")) { stop(paste0("CVE estimates not present in one or more `vaccine_est` ob", "jects; try rerunning `est_ce` with cve=TRUE.")) } else { df_add <- data.frame( x = obj$cve$s, y = obj$cve$est, ci_lower = obj$cve$ci_lower, ci_upper = obj$cve$ci_upper, curve = labels[counter] ) } } df_ests <- rbind(df_ests,df_add) counter <- counter + 1 } return(df_ests) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/plots.R
#' Calculate summary statistics #' #' @description TO DO #' @param dat A data object returned by `load_data`. #' @param quietly Boolean. If true, output will not be printed. #' @return A list containing values of various summary statistics. #' @examples #' data(hvtn505) #' dat <- load_data(time="HIVwk28preunblfu", event="HIVwk28preunbl", vacc="trt", #' marker="IgG_V2", covariates=c("age","BMI","bhvrisk"), #' weights="wt", ph2="casecontrol", data=hvtn505) #' summary_stats(dat=dat) #' @export summary_stats <- function(dat, quietly=FALSE) { if (!methods::is(dat,"vaccine_dat")) { stop(paste0("`dat` must be an object of class 'vaccine_dat' returned by lo", "ad_data().")) } dat_v <- dat[dat$a==1,] dat_p <- dat[dat$a==0,] num_ph1_subj_v <- length(dat_v$delta) num_ph1_subj_p <- length(dat_p$delta) num_ph2_subj_v <- sum(dat_v$z) num_ph2_subj_p <- sum(dat_p$z) num_ph1_events_v <- sum(dat_v$delta==1) num_ph1_events_p <- sum(dat_p$delta==1) num_ph2_events_v <- sum(dat_v$z==1 & dat_v$delta==1) num_ph2_events_p <- sum(dat_p$z==1 & dat_p$delta==1) ss <- list( "num_ph1_subj_v" = num_ph1_subj_v, "num_ph1_subj_p" = num_ph1_subj_p, "num_ph2_subj_v" = num_ph2_subj_v, "num_ph2_subj_p" = num_ph2_subj_p, "num_ph1_events_v" = num_ph1_events_v, "num_ph1_events_p" = num_ph1_events_p, "num_ph2_events_v" = num_ph2_events_v, "num_ph2_events_p" = num_ph2_events_p, "prop_ph1_events_v" = round(num_ph1_events_v/num_ph1_subj_v, 5), "prop_ph1_events_p" = round(num_ph1_events_p/num_ph1_subj_p, 5), "prop_ph2_events_v" = round(num_ph2_events_v/num_ph2_subj_v, 5), "prop_ph2_events_p" = round(num_ph2_events_p/num_ph2_subj_p, 5) ) if (!quietly) { # Number of subjects message(paste("Number of subjects (vaccine group, phase-1):", ss$num_ph1_subj_v)) message(paste("Number of subjects (placebo group, phase-1):", ss$num_ph1_subj_p)) message(paste("Number of subjects (vaccine group, phase-2):", ss$num_ph2_subj_v)) message(paste("Number of subjects (placebo group, phase-2):", ss$num_ph2_subj_p)) # Number of events message(paste("Number of events (vaccine group, phase-1):", ss$num_ph1_events_v)) message(paste("Number of events (placebo group, phase-1):", ss$num_ph1_events_p)) message(paste("Number of events (vaccine group, phase-2):", ss$num_ph2_events_v)) message(paste("Number of events (placebo group, phase-2):", ss$num_ph2_events_p)) # Event proportions message(paste("Proportion of subjects with an event (vaccine group, phase-", "1):", ss$prop_ph1_events_v)) message(paste("Proportion of subjects with an event (placebo group, phase-", "1):", ss$prop_ph1_events_p)) message(paste("Proportion of subjects with an event (vaccine group, phase-", "2):", ss$prop_ph2_events_v)) message(paste("Proportion of subjects with an event (placebo group, phase-", "2):", ss$prop_ph2_events_p)) } invisible(ss) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/summary_stats.R
#' @keywords internal "_PACKAGE" #' HVTN 505 Dataset #' #' A dataset from the HVTN 505 clinical trial #' #' @format A data frame with 1,950 rows and 10 variables: #' \itemize{ #' \item pub_id: Unique individual identifier #' \item trt: Treatment Assignment: 1=Vaccine, 0=Placebo #' \item HIVwk28preunbl: Indicator of HIV-1 infection diagnosis on/after study #' week 28 (day 196) prior to Unblinding Date (Apr 22, 2013). #' \item HIVwk28preunblfu: Follow-up time (in days) for HIV-1 infection #' diagnosis endpoint as of the Unblinding Date (22Apr2013) occuring #' on/after study week 28 (day 196). #' \item age: Age (in years) at randomization #' \item BMI: Body Mass Index: (Weight in Kg)/(Height in meters)**2 #' \item bhvrisk: Baseline behavioral risk score #' \item casecontrol: Indicator of inclusion in the case-control cohort #' \item wt: Inverse-probability-of-sampling weights, for the case-control #' cohort #' \item IgG_env: IgG Binding to gp120/140 #' \item IgG_V2: IgG Binding to V1V2 #' \item IgG_V3: IgG Binding to V3 #' } #' @source \url{https://atlas.scharp.org/cpas/project/HVTN\%20Public\%20Data/HVTN\%20505/begin.view} #' @docType data #' @keywords datasets #' @name hvtn505 #' @usage data(hvtn505) "hvtn505" ## usethis namespace: start #' @importFrom SuperLearner SuperLearner ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/vaccine/R/vaccine-package.R
.onAttach <- function(libname, pkgname) { vrs <- utils::packageVersion("vaccine") packageStartupMessage(paste0( "vaccine (version ", vrs, ").\nType ?vaccine to get started." )) }
/scratch/gouwar.j/cran-all/cranData/vaccine/R/zzz.R
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set(collapse=TRUE, comment = "#>", fig.width=6, fig.height=4, fig.align = "center") ## ----------------------------------------------------------------------------- library(vaccine) set.seed(123) ## ----------------------------------------------------------------------------- data(hvtn505) dat <- load_data( time = "HIVwk28preunblfu", event = "HIVwk28preunbl", vacc = "trt", marker = "IgG_V2", covariates = c("age","BMI","bhvrisk"), weights = "wt", ph2 = "casecontrol", data = hvtn505 ) ## ----------------------------------------------------------------------------- summary_stats(dat) ## ----------------------------------------------------------------------------- est_overall(dat=dat, t_0=578, method="KM") est_overall(dat=dat, t_0=578, method="Cox") ## ----------------------------------------------------------------------------- ests_cox <- est_ce(dat=dat, type="Cox", t_0=578) ests_np <- est_ce(dat=dat, type="NP", t_0=578) ## ----------------------------------------------------------------------------- plot_ce(ests_cox, ests_np) ## ----------------------------------------------------------------------------- plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) ## ----------------------------------------------------------------------------- ests_cox <- trim(ests_cox, dat=dat, quantiles=c(0.05,0.95)) ests_np <- trim(ests_np, dat=dat, quantiles=c(0.1,0.9)) plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) ## ----------------------------------------------------------------------------- library(ggplot2) my_plot <- plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) my_plot + labs(x="IgG Binding to V1V2") + scale_color_manual(labels = c("Cox model", "Nonparametric"), values = c("darkorchid3", "deepskyblue3")) + scale_fill_manual(labels = c("Cox model", "Nonparametric"), values = c("darkorchid3", "deepskyblue3")) ## ----------------------------------------------------------------------------- ests_table <- as_table(ests_cox, ests_np) head(ests_table)
/scratch/gouwar.j/cran-all/cranData/vaccine/inst/doc/basic.R
--- title: "Basic package workflow" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Basic package workflow} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set(collapse=TRUE, comment = "#>", fig.width=6, fig.height=4, fig.align = "center") ``` ```{R} library(vaccine) set.seed(123) ``` The `load_data` function takes in raw data and creates a data object that can be accepted by various estimation functions. We use publicly-avaliable data from the HVTN 505 HIV vaccine efficacy trial as our example. ```{R} data(hvtn505) dat <- load_data( time = "HIVwk28preunblfu", event = "HIVwk28preunbl", vacc = "trt", marker = "IgG_V2", covariates = c("age","BMI","bhvrisk"), weights = "wt", ph2 = "casecontrol", data = hvtn505 ) ``` The `summary_stats` function gives us some useful summaries of the dataset. ```{R} summary_stats(dat) ``` The `est_overall` function allows us to estimate overall risk in the placebo and vaccine groups, as well as estimate vaccine efficacy, using either a nonparametric Kaplan-Meier estimator or a marginalized Cox model. ```{R} est_overall(dat=dat, t_0=578, method="KM") est_overall(dat=dat, t_0=578, method="Cox") ``` The `est_ce` function allows us to compute controlled effects curves; see [Gilbert, Fong, Kenny, and Carone 2022](https://academic.oup.com/biostatistics/article-abstract/24/4/850/7320953) for more detail. ```{R} ests_cox <- est_ce(dat=dat, type="Cox", t_0=578) ests_np <- est_ce(dat=dat, type="NP", t_0=578) ``` The `plot_ce` function produces basic plots of CR or CVE curves. ```{R} plot_ce(ests_cox, ests_np) ``` Use the `density` option to add a kernel density estimate of the distribution of the marker to the plot background. ```{R} plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) ``` Use the `trim` function to truncate the display of the curves, based on quantiles of the marker distribution. It is recommended to truncate the display of the nonparametric curves, as estimates can be biased towards the endpoints of the marker distribution. ```{R} ests_cox <- trim(ests_cox, dat=dat, quantiles=c(0.05,0.95)) ests_np <- trim(ests_np, dat=dat, quantiles=c(0.1,0.9)) plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) ``` Plots generated using `plot_ce` can be further customized using `ggplot2` functions. For example, we change the plot labels and colors as follows. ```{R} library(ggplot2) my_plot <- plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) my_plot + labs(x="IgG Binding to V1V2") + scale_color_manual(labels = c("Cox model", "Nonparametric"), values = c("darkorchid3", "deepskyblue3")) + scale_fill_manual(labels = c("Cox model", "Nonparametric"), values = c("darkorchid3", "deepskyblue3")) ``` To view estimates in tabular format, use the `as_table` function. ```{R} ests_table <- as_table(ests_cox, ests_np) head(ests_table) ```
/scratch/gouwar.j/cran-all/cranData/vaccine/inst/doc/basic.Rmd
--- title: "Basic package workflow" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Basic package workflow} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set(collapse=TRUE, comment = "#>", fig.width=6, fig.height=4, fig.align = "center") ``` ```{R} library(vaccine) set.seed(123) ``` The `load_data` function takes in raw data and creates a data object that can be accepted by various estimation functions. We use publicly-avaliable data from the HVTN 505 HIV vaccine efficacy trial as our example. ```{R} data(hvtn505) dat <- load_data( time = "HIVwk28preunblfu", event = "HIVwk28preunbl", vacc = "trt", marker = "IgG_V2", covariates = c("age","BMI","bhvrisk"), weights = "wt", ph2 = "casecontrol", data = hvtn505 ) ``` The `summary_stats` function gives us some useful summaries of the dataset. ```{R} summary_stats(dat) ``` The `est_overall` function allows us to estimate overall risk in the placebo and vaccine groups, as well as estimate vaccine efficacy, using either a nonparametric Kaplan-Meier estimator or a marginalized Cox model. ```{R} est_overall(dat=dat, t_0=578, method="KM") est_overall(dat=dat, t_0=578, method="Cox") ``` The `est_ce` function allows us to compute controlled effects curves; see [Gilbert, Fong, Kenny, and Carone 2022](https://academic.oup.com/biostatistics/article-abstract/24/4/850/7320953) for more detail. ```{R} ests_cox <- est_ce(dat=dat, type="Cox", t_0=578) ests_np <- est_ce(dat=dat, type="NP", t_0=578) ``` The `plot_ce` function produces basic plots of CR or CVE curves. ```{R} plot_ce(ests_cox, ests_np) ``` Use the `density` option to add a kernel density estimate of the distribution of the marker to the plot background. ```{R} plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) ``` Use the `trim` function to truncate the display of the curves, based on quantiles of the marker distribution. It is recommended to truncate the display of the nonparametric curves, as estimates can be biased towards the endpoints of the marker distribution. ```{R} ests_cox <- trim(ests_cox, dat=dat, quantiles=c(0.05,0.95)) ests_np <- trim(ests_np, dat=dat, quantiles=c(0.1,0.9)) plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) ``` Plots generated using `plot_ce` can be further customized using `ggplot2` functions. For example, we change the plot labels and colors as follows. ```{R} library(ggplot2) my_plot <- plot_ce(ests_cox, ests_np, density_type="kde", dat=dat) my_plot + labs(x="IgG Binding to V1V2") + scale_color_manual(labels = c("Cox model", "Nonparametric"), values = c("darkorchid3", "deepskyblue3")) + scale_fill_manual(labels = c("Cox model", "Nonparametric"), values = c("darkorchid3", "deepskyblue3")) ``` To view estimates in tabular format, use the `as_table` function. ```{R} ests_table <- as_table(ests_cox, ests_np) head(ests_table) ```
/scratch/gouwar.j/cran-all/cranData/vaccine/vignettes/basic.Rmd
#' Returns the typical value from a unit-normal distribution #' @description #' Returns the typical value from a unit-normal distribution for the #' \emph{i}th ordered observation in an \emph{n}-sized sample. #' #' This is a helper function for FUNOP, which uses the output of this #' function as the denominator for its slope calculation. #' @param #' i Non-zero index of an array #' @param #' n Non-zero length of the array #' @return #' Quantile of \code{i} from a unit-normal distribution #' @seealso [vacuum::funop()] #' @references #' Tukey, John W. "The Future of Data Analysis." #' \emph{The Annals of Mathematical Statistics}, #' \emph{33}(1), 1962, pp 1-67. \emph{JSTOR}, #' \url{https://www.jstor.org/stable/2237638}. #' @examples #' a_qnorm(i = 25, n = 42) #' a_qnorm(21.5, 42) #' @export a_qnorm <- function(i, n) { if (is.numeric(i) & is.numeric(n)) { stats::qnorm((3 * i - 1) / (3 * n + 1)) } else { warning('arguments "i" and "n" must be numeric') } }
/scratch/gouwar.j/cran-all/cranData/vacuum/R/a_qnorm.R
#' Identifies outliers in a numeric vector #' @description #' FUNOP stands for FUll NOrmal Plot. #' #' The procedure identifies outliers by calculating their slope (\code{z}), #' relative to the vector's median. #' #' The procedure ignores values in the middle third of the \emph{ordered} #' vector. The remaining values are all candidates for consideration. The #' slopes of all candidates are calculated, and the median of their slopes #' is used as the primary basis for identifying outliers. #' #' Any value whose slope is \code{B} times larger than the median slope is #' identified as an outlier. Additionally, any value whose \emph{magnitude} #' is larger than that of the slope-based outliers is also identified as #' an outlier. #' #' However, the procedure will \emph{not} identify as outliers any values #' within \code{A} standard deviations of the vector's median (i.e., not #' the median of candidate slopes). #' @param x #' Numeric vector to inspect for outliers (does not need to be ordered) #' @param A #' Number of standard deviations beyond the median of \code{x} #' @param B #' Multiples beyond the median slope of candidate values #' @return #' A data frame containing one row for every member of \code{x} (in the same #' order as \code{x}) and the #' following columns: #' * \code{y}: Original values of vector \code{x} #' * \code{i}: Ordinal position of value \code{y} in the sorted vector \code{x} #' * \code{middle}: Boolean indicating whether ordinal position \code{i} is in the middle third of the vector #' * \code{a}: Result of \code{a_qnorm(i, length(x))} #' * \code{z}: Slope of \code{y} relative to \code{median(y)} #' * \code{special}: Boolean indicating whether \code{y} is an outlier #' @seealso [vacuum::a_qnorm()] #' @references #' Tukey, John W. "The Future of Data Analysis." #' \emph{The Annals of Mathematical Statistics}, #' \emph{33}(1), 1962, pp 1-67. \emph{JSTOR}, #' \url{https://www.jstor.org/stable/2237638}. #' @examples #' funop(c(1, 2, 3, 11)) #' funop(table_1) #' #' attr(funop(table_1), 'z_split') #' @export funop <- function(x, A = 0, B = 1.5) { special <- orig_order <- y <- i <- middle <- a <- z <- NULL if (!is.vector(x) | !is.numeric(x)) { warning('argument "x" must be a numeric vector') } else if (length(A) != 1 | !is.numeric(A)) { warning('argument "A" must be a single numeric value') } else if (length(B) != 1 | !is.numeric(B)) { warning('argument "B" must be a single numeric value') } else if (anyNA(c(A, B))) { warning('arguments "A" and "B" must be single numeric values') } else { # (b1) # Let a_{i|n} be a typical value for the ith ordered observation in # a sample of n from a unit normal distribution. n <- length(x) # initialze dataframe to hold results result <- data.frame( y = x, orig_order = 1:n, a = NA, z = NA, middle = FALSE, special = FALSE ) # put array in order result <- result %>% dplyr::arrange(x) %>% dplyr::mutate(i = dplyr::row_number()) # calculate a_{i|n} result$a <- a_qnorm(result$i, n) # (b2) # Let y_1 ≤ y_2 ≤ … ≤ y_n be the ordered values to be examined. # Let y_split be their median (or let y_trimmed be the mean of the y_i # with (1/3)n < i ≤ (2/3)n). middle_third <- (floor(n / 3) + 1):ceiling(2 * n / 3) outer_thirds <- (1:n)[-middle_third] result$middle[middle_third] <- TRUE y_split <- stats::median(result$y) y_trimmed <- mean(result$y[middle_third]) # (b3) # For i ≤ (1/3)n or > (2/3)n only, # let z_i = (y_i – y_split) / a_{i|n} # (or let z_i = (y_i – y_trimmed) / a_{i|n}). result$z[outer_thirds] <- (result$y[outer_thirds] - y_split) / result$a[outer_thirds] # (b4) # Let z_split be the median of the z’s thus obtained. z_split <- stats::median(result$z[outer_thirds]) # (b5) # Give special attention to z’s for which both # |y_i – y_split| ≥ A · z_split and z_i ≥ B · z_split # where A and B are prechosen. result$special <- ifelse(result$z >= (B * z_split) & abs(result$y - y_split) >= (A * z_split), TRUE, FALSE) # (b5*) # Particularly for small n, z_j’s with j more extreme than an i # for which (b5) selects z_i also deserve special attention. # in the top third, look for values larger than ones already found top_third <- outer_thirds[outer_thirds > max(middle_third)] # take advantage of the fact that we've already indexed our result set # and simply look for values of i larger than the smallest i in the # top third (further to the right of our x-axis) if (any(result$special[top_third])) { min_i <- result[top_third, ] %>% dplyr::filter(special == TRUE) min_i <- min(min_i$i) result$special[which(result$i > min_i)] <- TRUE } # in the top third, look for values smaller than ones already found bottom_third <- outer_thirds[outer_thirds < min(middle_third)] # look for values of i smaller than the largest i in the bottom third # (further to the left of our x-axis) if (any(result$special[bottom_third])) { max_i <- result[bottom_third, ] %>% dplyr::filter(special == TRUE) max_i <- max(max_i$i) result$special[which(result$i < max_i)] <- TRUE } result <- result %>% dplyr::arrange(orig_order) %>% dplyr::select(y, i, middle, a, z, special) attr(result, 'y_split') <- y_split attr(result, 'y_trimmed') <- y_trimmed attr(result, 'z_split') <- z_split result } }
/scratch/gouwar.j/cran-all/cranData/vacuum/R/funop.R
#' Identifies and treats outliers in a two-way table #' @description #' FUNOR-FUNOM stands for FUll NOrmal Rejection-FUll NOrmal Modification. #' #' The procedure treats a two-way (contingency) table for outliers by #' isolating residuals from the table's likely systemic effects, which #' are calculated from the table's grand, row, and column means. #' #' The residuals are passed to separate \emph{rejection} (FUNOR) and #' \emph{modification} (FUNOM) procedures, which both depend upon FUNOP #' to identify outliers. As such, this procedure requires two sets of #' \code{A} and \code{B} parameters. #' #' The procedure treats outliers by reducing their residuals, resulting #' in values that are much closer to their expected values (i.e., #' combined grand, row, and column effects). #' @param x #' Two-way table to treat for outliers #' @param A_r #' A for the FUNOR phase (see FUNOP for details) #' @param B_r #' B for the FUNOR phase #' slope #' @param A_m #' A for the FUNOM phase (\code{A_m} is usually 0) #' @param B_m #' B for the FUNOM phase #' @return #' A two-way table of the same size as \code{x}, treated for outliers. #' @seealso [vacuum::funop()] #' @references #' Tukey, John W. "The Future of Data Analysis." #' \emph{The Annals of Mathematical Statistics}, #' \emph{33}(1), 1962, pp 1-67. \emph{JSTOR}, #' \url{https://www.jstor.org/stable/2237638}. #' @examples #' funor_funom(table_2) #' which(funor_funom(table_2) != table_2) #' @export funor_funom <- function(x, A_r = 10, B_r = 1.5, A_m = 0, B_m = 1.5) { j <- k <- change_type <- j_mean <- k_mean <- y <- special <- i <- middle <- a <- z <- interesting_values <- new_x <- NULL x <- as.matrix(x) if (!is.matrix(x) | !is.numeric(x)) { warning('argument "x" must be convertable to a numeric matrix') } else if (nrow(x) < 2 | ncol(x) < 2) { # change_factor will divide by zero if r = 1 or c = 1 warning('argument "x" must have at least 2 rows and columns') } else if (!is.numeric(c(A_r, B_r, A_m, B_m))) { warning('arguments "A" and "B" must be single numeric values') } else if (length(c(A_r, B_r, A_m, B_m)) != 4) { warning('arguments "A" and "B" must be single numeric values') } else if (anyNA(c(A_r, B_r, A_m, B_m))) { warning('arguments "A" and "B" must be single numeric values') } else { # Initialize r <- nrow(x) c <- ncol(x) n <- r * c # this will be used in step a3, but only need to calc once change_factor <- r * c / ((r - 1) * (c - 1)) # this data frame makes it easy to track all values # j and k are the rows and columns of the table dat <- data.frame( x = as.vector(x), j = ifelse(1:n %% r == 0, r, 1:n %% r), k = ceiling(1:n / r), change_type = 0 ) ########### ## FUNOR ## ########### #repeat { # Tukey's original definition says to repeat until no more outliers # are found, but in some cases (maybe just very small tables with # little variance) we might end up looping more times than Tukey # intended. Other stopping criteria to consider: No more than j * k # passes, or no more than one change per y_{jk} # for (ctr in 1:n) { # don't repeat for more members than are in dataset dat <- dat %>% dplyr::select(x, j, k, change_type) # this removes the calculated values from last loop # (a1) # Fit row and column means to the original observations # and form the residuals # calculate the row means dat <- dat %>% dplyr::group_by(j) %>% dplyr::summarise(j_mean = mean(x)) %>% dplyr::ungroup() %>% dplyr::select(j, j_mean) %>% dplyr::inner_join(dat, by = 'j') # calculate the column means dat <- dat %>% dplyr::group_by(k) %>% dplyr::summarise(k_mean = mean(x)) %>% dplyr::ungroup() %>% dplyr::select(k, k_mean) %>% dplyr::inner_join(dat, by = 'k') grand_mean <- mean(dat$x) # calculate the residuals dat$y <- dat$x - dat$j_mean - dat$k_mean + grand_mean # put dat in order based upon y (which will match i in FUNOP) dat <- dat %>% dplyr::arrange(y) %>% dplyr::mutate(i = dplyr::row_number()) # (a2) # apply FUNOP to the residuals funop_residuals <- funop(dat$y, A_r, B_r) # (a4) # repeat until no y_{jk} deserves special attention if (!any(funop_residuals$special)) { break } # (a3) modify x_{jk} for largest y_{jk} that deserves special attention big_y <- funop_residuals %>% dplyr::filter(special == TRUE) %>% dplyr::top_n(1, (abs(y))) # change x by an amount that's proportional to its # position in the distribution (a) # here's why it's useful to have z be on same scale as the raw value delta_x <- big_y$z * big_y$a * change_factor dat$x[which(dat$i == big_y$i)] <- big_y$y - delta_x dat$change_type[which(dat$i == big_y$i)] <- 1 #dat[which(dat$i == big_y$i), c('j', 'k')] #attr(funop_residuals, 'y_split') #attr(funop_residuals, 'z_split') #delta_x } # Done with FUNOR. To apply subsequent modifications we need # the following from the most recent FUNOP dat <- funop_residuals %>% dplyr::select(i, middle, a, z) %>% dplyr::inner_join(dat, by = 'i') z_split <- attr(funop_residuals, 'z_split') y_split <- attr(funop_residuals, 'y_split') ########### ## FUNOM ## ########### # (a5) # identify new interesting values based upon new A & B # start with threshold for extreme B extreme_B <- B_m * z_split dat <- dat %>% dplyr::mutate(interesting_values = ((middle == FALSE) & (z >= extreme_B))) # logical AND with threshold for extreme A extreme_A <- A_m * z_split dat$interesting_values <- ifelse(dat$interesting_values & (abs(dat$y - y_split) >= extreme_A), TRUE, FALSE) # (a6) # adjust just the interesting values delta_x <- dat %>% dplyr::filter(interesting_values == TRUE) %>% dplyr::mutate(change_type = 2) %>% dplyr::mutate(delta_x = (z - extreme_B) * a) %>% dplyr::mutate(new_x = x - delta_x) %>% dplyr::select(-x, -delta_x) %>% dplyr::rename(x = new_x) # select undistinguied values from dat and recombine with # adjusted versions of the interesting values dat <- dat %>% dplyr::filter(interesting_values == FALSE) %>% dplyr::bind_rows(delta_x) # return data to original shape dat <- dat %>% dplyr::select(j, k, x, change_type) %>% dplyr::arrange(j, k) # reshape result into a table of the original shape matrix(dat$x, nrow = r, byrow = TRUE) } }
/scratch/gouwar.j/cran-all/cranData/vacuum/R/funor_funom.R
#' Table 1 #' #' Example data taken from Table 1 of John Tukey's #' "Future of Data Analysis." #' #' @name table_1 #' @docType data #' @format A numeric vector containing 14 elements. #' #' @source #' Tukey, John W. "The Future of Data Analysis." #' \emph{The Annals of Mathematical Statistics}, #' \emph{33}(1), 1962, pp 1-67. \emph{JSTOR}, #' \url{https://www.jstor.org/stable/2237638}. #' #' @examples #' table_1 #' funop(table_1) "table_1"
/scratch/gouwar.j/cran-all/cranData/vacuum/R/table_1.R
#' Table 2 #' #' Example data taken from Table 2 of John Tukey's #' "Future of Data Analysis." #' #' @name table_2 #' @docType data #' @format A 36x15 numeric matrix. #' #' @source #' Tukey, John W. "The Future of Data Analysis." #' \emph{The Annals of Mathematical Statistics}, #' \emph{33}(1), 1962, pp 1-67. \emph{JSTOR}, #' \url{https://www.jstor.org/stable/2237638}. #' #' @examples #' table_2 #' funor_funom(table_2) "table_2"
/scratch/gouwar.j/cran-all/cranData/vacuum/R/table_2.R
#' Table 8 #' #' Example data taken from Table 8 of John Tukey's #' "Future of Data Analysis." Note that this dataset fixes #' a typo in the original document: Column 23, row 10 contains #' 0.100, corrected from the original -0.100. #' #' @name table_8 #' @docType data #' @format A 36x15 numeric matrix. #' #' @source #' Tukey, John W. "The Future of Data Analysis." #' \emph{The Annals of Mathematical Statistics}, #' \emph{33}(1), 1962, pp 1-67. \emph{JSTOR}, #' \url{https://www.jstor.org/stable/2237638}. #' #' @examples #' table_8 #' vacuum_cleaner(table_8) "table_8"
/scratch/gouwar.j/cran-all/cranData/vacuum/R/table_8.R
#' Pipe operator #' #' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs NULL
/scratch/gouwar.j/cran-all/cranData/vacuum/R/utils-pipe.R
#' @keywords internal "_PACKAGE" # The following block is used by usethis to automatically manage # roxygen namespace tags. Modify with care! ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/vacuum/R/vacuum-package.R
#' @keywords internal "_PACKAGE" # The following block is used by usethis to automatically manage # roxygen namespace tags. Modify with care! ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/vacuum/R/vacuum.R
l2_norm <- function(v) { v ^ 2 %>% sum() %>% sqrt } #' Returns the residuals of a two-way table after removing systemic effects #' @description #' To remove systemic effects from values in a contingency table, #' vacuum cleaner uses regression to identify the table's main effect #' (dual regression), row effect (deviations of row #' regression from dual regression), and column effect (deviations of #' column regression from dual regression). #' #' Regression is performed twice: First on the table's original values, #' then on the resulting residuals. The output is a table of residuals #' "vacuum cleaned" of likely systemic effects. #' @param x #' Two-way table to analyze (must be 3x3 or greater). #' @return #' Residuals of \code{x} #' @seealso #' [vacuum::funop()], [vacuum::funor_funom()] #' @references #' Tukey, John W. "The Future of Data Analysis." #' \emph{The Annals of Mathematical Statistics}, #' \emph{33}(1), 1962, pp 1-67. \emph{JSTOR}, #' \url{https://www.jstor.org/stable/2237638}. #' @examples #' vacuum_cleaner(table_8) #' @export vacuum_cleaner <- function(x) { x <- as.matrix(x) if (!is.matrix(x) | !is.numeric(x)) { warning('argument "x" must be convertable to a numeric matrix') } else if (nrow(x) < 3 | ncol(x) < 3) { warning('argument "x" must have at least 3 rows and columns') # (p 53) } else { input_table <- x r <- nrow(input_table) c <- ncol(input_table) ###################### ## Initial carriers ## ###################### # sqrt(1/n) carrier_r <- rep(sqrt(1 / r), r) carrier_c <- rep(sqrt(1 / c), c) ################### ## Start of loop ## ################### # Tukey passes through the loop twice. # Suggests further passes possible in the "attachments" section (p 53) for (pass in 1:2) { ################## ## Coefficients ## ################## # Calculate the column coefficients coef_c <- rep(NA, c) for (i in 1:c) { # loop through every column, summing every row # denominator is based upon the number of rows in the column coef_c[i] <- sum(carrier_r * input_table[, i]) / sum(carrier_r ^ 2) } # Calculate the row coefficients coef_r <- rep(NA, r) for (i in 1:r) { # loop through every row, summing every column # denominator is based upon the number of columns in the row coef_r[i] <- sum(carrier_c * input_table[i, ]) / sum(carrier_c ^ 2) } ########## ## y_ab ## ########## # either one of these y_ab <- sum(coef_c * carrier_c) / sum(carrier_c ^ 2) y_ab <- sum(carrier_r * coef_r) / sum(carrier_r ^ 2) ######################## ## Apply subprocedure ## ######################## # create a destination for the output output_table <- input_table for (i in 1:r) { for (j in 1:c) { output_table[i, j] <- input_table[i, j] - carrier_r[i] * (coef_c[j] - carrier_c[j] * y_ab) - carrier_c[j] * (coef_r[i] - carrier_r[i] * y_ab) - y_ab * carrier_c[j] * carrier_r[i] } } # These are the coefficients that will get carried forward coef_c <- coef_c - carrier_c * y_ab coef_r <- coef_r - carrier_r * y_ab ######### ## aov ## ######### #sum(coef_c ^ 2) #var(coef_c) # #sum(coef_r ^ 2) #var(coef_r) # #dat <- output_table %>% # dplyr::mutate('row' = dplyr::row_number()) %>% # tidyr::pivot_longer(cols = starts_with('X'), # names_to = 'col', # values_to = 'value') # #dat$row <- as.factor(dat$row) # #aov_results <- aov(value ~ row + col, dat) #summary(aov_results) ######################## ## Prep for next pass ## ######################## # normalize coefficients because we want sqrt(sum(a^2)) == 1 carrier_r <- coef_r / l2_norm(coef_r) carrier_c <- coef_c / l2_norm(coef_c) input_table <- output_table ################# ## End of loop ## ################# } output_table } }
/scratch/gouwar.j/cran-all/cranData/vacuum/R/vacuum_cleaner.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup, include = FALSE--------------------------------------------------- library(vacuum) library(ggplot2) library(magrittr) library(tidyr) library(dplyr) ## ----echo = FALSE, fig.width = 7, fig.height = 4------------------------------ # Normal Q-Q plot for Tukey's sample data data.frame(y = table_1) %>% ggplot(aes(sample = y)) + stat_qq() + stat_qq_line() + #geom_abline(aes(intercept = 0, slope = 1)) + labs(title = 'Normal Q-Q plot of sample data') ## ----echo = FALSE, fig.width = 7, fig.height = 4------------------------------ x <- table_1 n <- length(x) y_split <- median(x) dat <- data.frame(i = 1:n, y_sorted = sort(x), a = a_qnorm(1:n, n), z = (sort(x) - y_split) / a_qnorm(1:n, n) ) # find the point with the greatest slope key_pt <- dat[which.max(dat$z), ] # plot the points and the slope of the point key point ggplot(dat, aes(x = a, y = y_sorted)) + geom_point(color = 'darkgrey') + geom_point(dat = key_pt, aes(x = a, y = y_sorted), color = 'black') + geom_point(aes(x = 0, y = y_split), color = 'red') + # example line geom_segment(aes(x = 0, y = y_split, xend = key_pt$a, yend = key_pt$y_sorted)) + labs(title = 'Sorted values of y plotted against theoretical distribution a(y)', y = 'y') ## ----echo = FALSE, , fig.width = 7, fig.height = 4---------------------------- A <- 0 B <- 1.5 tmp <- funop(table_1, A, B) # need z & special for every point tmp$z <- (tmp$y - median(tmp$y)) / a_qnorm(tmp$i, n) tmp$special[is.na(tmp$special)] <- FALSE # need outer to get special and outer to add up as a factor tmp$outer <- !tmp$middle z_split <- attr(tmp, 'z_split') y_split <- attr(tmp, 'y_split') extreme_B <- B * z_split extreme_A <- A * z_split ggplot(tmp, aes(x = y, y = z)) + geom_point(aes(color = as.factor(outer + special))) + geom_hline(yintercept = z_split) + geom_hline(yintercept = extreme_B, color = 'blue', alpha = 0.5) + geom_vline(xintercept = y_split, color = 'green3', alpha = 0.75) + geom_rect( xmin = -Inf, xmax = Inf, ymin = extreme_B, ymax = Inf, alpha = 0.0075, fill = 'blue' ) + geom_rect( xmin = y_split - extreme_A, xmax = y_split + extreme_A, ymin = -Inf, ymax = Inf, alpha = 0.01, fill = 'green' ) + labs(title = 'FUNOP: slope (z) plotted against original values') + labs(x = 'original values') + scale_color_manual( name = 'values', labels = c( 'excluded', 'undistinguished', 'special attention' ), values = c('green3', 'black', 'red') ) ## ----------------------------------------------------------------------------- # Table 1 contains example data from Tukey's paper table_1 result <- funop(table_1) result # value of the outliers result[which(result$special == TRUE), 'y'] ## ----echo = FALSE, fig.width = 7, fig.height = 4------------------------------ # cleanse the table cleansed_t2 <- funor_funom(table_2) data.frame( i = 1:length(table_2), original = as.vector(table_2), cleansed = as.vector(cleansed_t2) ) %>% ggplot(aes(x = i)) + geom_point(aes(y = original), color = 'black') + geom_segment(aes( x = i, y = original, xend = i, yend = cleansed ), color = 'black', linetype = 'dashed') + geom_point(aes(y = cleansed), color = 'grey') + labs(title = 'Changes to Table 2', y = 'value', x = '') ## ----------------------------------------------------------------------------- # create a random dataset, representing a two-way table set.seed(42) dat <- matrix(rnorm(16), nrow = 4) # add some noise dat[2, 1] <- rnorm(1, mean = 10) # cleanse the table of outliers cleansed_dat <- funor_funom(dat) # look at the two tables, before and after dat cleansed_dat # look at the difference between the two tables # only one non-zero difference dat - cleansed_dat ## ----------------------------------------------------------------------------- # convert the output of vacuum_cleaner into a long data frame dat <- vacuum_cleaner(table_8) %>% as.data.frame() %>% dplyr::mutate('row' = dplyr::row_number()) %>% tidyr::pivot_longer(cols = dplyr::starts_with('V'), names_to = 'col', values_to = 'value') # since the table_8 was a two-way table, the rows are factors dat$row <- as.factor(dat$row) # conduct analysis of variance aov_results <- aov(value ~ row + col, dat) summary(aov_results)
/scratch/gouwar.j/cran-all/cranData/vacuum/inst/doc/vacuum-vignette.R
--- title: "Vacuum Vignette" author: "Ron Sielinski" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Vacuum Vignette} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup, include = FALSE} library(vacuum) library(ggplot2) library(magrittr) library(tidyr) library(dplyr) ``` ## A tidy implementation of John Tukey's vacuum cleaner One of John Tukey’s landmark papers, “The Future of Data Analysis” [1], contains a set of analytical procedures that focus on the analysis of two-way (contingency) tables. **Vacuum** contains an implementation of the three procedures: * FUNOP (**FU**ll **NO**rmal **P**lot): Identifies outliers within a vector by calculating the slope (*z*) of every element, relative to the vector's median. * FUNOR-FUNOM (**FU**ll **NO**rmal **R**ejection-**FU**ll **NO**rmal **M**odification): Treats a two-way (contingency) table for outliers by isolating residuals from the table's likely systemic effects, which are calculated from the table's grand, row, and column means. * Vacuum cleaner: Removes systemic effects from values in a two-way table, returning a set of residuals that can be used for further examination (e.g., analysis of variance). ### FUNOP The base prodecure is FUNOP, which identifies outliers in a vector. Here’s Tukey’s definition: >(b1) Let *a~i|n~* be a typical value for the *i*th ordered observation in a sample of *n* from a unit normal distribution. >(b2) Let *y*~1~ ≤ *y*~2~ ≤ … ≤ *y*~n~ be the ordered values to be examined. Let *y̍* be their median (or let *y̆*, read “y trimmed”, be the mean of the *y~i~* with \frac{1}{3}*n* < *i* ≤ \frac{1}{3}(2*n*). >(b3) For *i* ≤ ⅓*n* or > ⅓(2*n*) only, let *z~i~* = (*y~i~* – *y̍*)/*a~i|n~* (or let *z~i~* = (*y~i~* – *y̆*) /*a~i|n~*). >(b4) Let *z̍* be the median of the *z*’s thus obtained (about \frac{1}{3}(2*n*) in number). >(b5) Give special attention to *z*’s for which both |*y~i~* – *y̍*| ≥ A · *z̍* and *z~i~* ≥ B · *z̍* where A and B are prechosen. >(b5*) Particularly for small *n*, *z~j~*’s with *j* more extreme than an *i* for which (b5) selects *z~i~* also deserve special attention… (p 23). The basic idea is very similar to a Q-Q plot. Tukey gives us a sample of 14 data points. On a normal Q-Q plot, if data are normally distributed, they form a straight line. But in the chart below, based upon data from Tukey’s example, we can clearly see that a couple of the points are relatively distant from the straight line. They’re outliers. ```{r echo = FALSE, fig.width = 7, fig.height = 4} # Normal Q-Q plot for Tukey's sample data data.frame(y = table_1) %>% ggplot(aes(sample = y)) + stat_qq() + stat_qq_line() + #geom_abline(aes(intercept = 0, slope = 1)) + labs(title = 'Normal Q-Q plot of sample data') ``` The goal of FUNOP, though, is to eliminate the need for visual inspection by automating interpretation. The first variable in the FUNOP procedure (*a~i|n~*) simply gives us the theoretical distribution, where *i* is the ordinal position in the range 1..*n* and Gau^-1^ is the quantile function of the normal distribution (i.e., the “Q” in Q-Q plot): $$ a_{i|n}=\ {\rm Gau}^{-1}\left[\frac{\left(3i-1\right)}{\left(3n+1\right)}\right] $$ The key innovation of FUNOP is to calculate the slope of each point, relative to the median. ``` {r echo = FALSE, fig.width = 7, fig.height = 4} x <- table_1 n <- length(x) y_split <- median(x) dat <- data.frame(i = 1:n, y_sorted = sort(x), a = a_qnorm(1:n, n), z = (sort(x) - y_split) / a_qnorm(1:n, n) ) # find the point with the greatest slope key_pt <- dat[which.max(dat$z), ] # plot the points and the slope of the point key point ggplot(dat, aes(x = a, y = y_sorted)) + geom_point(color = 'darkgrey') + geom_point(dat = key_pt, aes(x = a, y = y_sorted), color = 'black') + geom_point(aes(x = 0, y = y_split), color = 'red') + # example line geom_segment(aes(x = 0, y = y_split, xend = key_pt$a, yend = key_pt$y_sorted)) + labs(title = 'Sorted values of y plotted against theoretical distribution a(y)', y = 'y') ``` If *y̍* is the median of the sample, and we presume that it’s located at the midpoint of the distribution (where *a*(*y*) = 0), then the slope of each point can be calculated as: $$ z_i=\frac{y_i - \acute{y}}{a_{i|n}} $$ The chart above illustrates how slope of one point (1.2, 454) is calculated, relative to the median (0, 33.5). $$ z\ =\ \frac{\Delta y}{\Delta a}\ =\ \frac{\left(454.0-\ 33.5\right)}{\left(1.2-0\right)}=350.4 $$ Any point that has a slope significantly steeper than the rest of the population is necessarily farther from the straight line. To do this, FUNOP simply compares each slope (*z~i~*) to the median of all *calculated* slopes (*z̍*). Note, however, that FUNOP calculates slopes for the top and bottom thirds of the sorted population only, in part because *z~i~* won’t vary much over the inner third, but also because the value of *a~i|n~* for the inner third will be close to 0 and dividing by ≈0 when calculating *z~i~* might lead to instability. Significance---what Tukey calls “special attention”---is partially determined by *B*, one of two predetermined values (or hyperparameters). For his example, Tukey recommends a value between 1.5 and 2.0, which means that FUNOP simply checks whether the slope of any point, relative to the midpoint, is 1.5 or 2.0 times larger than the median. The other predetermined value is *A*, which is roughly equivalent to the number of standard deviations of *y~i~* from *y̍* and serves as a second criterion for significance. The following chart shows how FUNOP works. ``` {r echo = FALSE, , fig.width = 7, fig.height = 4} A <- 0 B <- 1.5 tmp <- funop(table_1, A, B) # need z & special for every point tmp$z <- (tmp$y - median(tmp$y)) / a_qnorm(tmp$i, n) tmp$special[is.na(tmp$special)] <- FALSE # need outer to get special and outer to add up as a factor tmp$outer <- !tmp$middle z_split <- attr(tmp, 'z_split') y_split <- attr(tmp, 'y_split') extreme_B <- B * z_split extreme_A <- A * z_split ggplot(tmp, aes(x = y, y = z)) + geom_point(aes(color = as.factor(outer + special))) + geom_hline(yintercept = z_split) + geom_hline(yintercept = extreme_B, color = 'blue', alpha = 0.5) + geom_vline(xintercept = y_split, color = 'green3', alpha = 0.75) + geom_rect( xmin = -Inf, xmax = Inf, ymin = extreme_B, ymax = Inf, alpha = 0.0075, fill = 'blue' ) + geom_rect( xmin = y_split - extreme_A, xmax = y_split + extreme_A, ymin = -Inf, ymax = Inf, alpha = 0.01, fill = 'green' ) + labs(title = 'FUNOP: slope (z) plotted against original values') + labs(x = 'original values') + scale_color_manual( name = 'values', labels = c( 'excluded', 'undistinguished', 'special attention' ), values = c('green3', 'black', 'red') ) ``` Our original values are plotted along the *x*-axis. The points in the green make up the inner third of our sample, and we use them to calculate *y̍*, the median of just those points, indicated by the green vertical line. The points not in green make up the outer thirds (i.e., the top and bottom thirds) of our sample, and we use them to calculate *z̍*, the median slope of just those points, indicated by the black horizontal line. Our first selection criterion is *z~i~* ≥ *B* · *z̍*. In his example, Tukey sets *B* = 1.5, so our threshold of interest is 1.5*z̍*, indicated by the blue horizontal line. We’ll consider any point above that line (the shaded blue region) to “deserve special attention”. We have only one such point, colored red. Our second criterion is |*y~i~* – *y̍*| ≥ *A* · *z̍*. In his example, Tukey sets *A* = 0, so our threshold of interest is |*y~i~* – *y̍*| ≥ 0 or (more simply) *y~i~* ≠ *y̍*. Basically, any point not on the green line. Our one point in the shaded blue region isn’t on the green line, so we still have our one point. Our final criterion is any *z~j~*’s with *j* more extreme than any *i* selected so far. Basically, that’s any value more extreme than the ones already identified. In this case, we have one value that’s larger (further to the right on the *x*-axis) than our red dot. That point is also colored red, and we flag it as deserving special attention. The two points identified by FUNOP are the same ones that we identified visually in Chart 1. ```{r} # Table 1 contains example data from Tukey's paper table_1 result <- funop(table_1) result # value of the outliers result[which(result$special == TRUE), 'y'] ``` ### FUNOR-FUNOM A common reason for identifing outliers is to do something about them, often by trimming or Winsorizing the dataset. The former simply removes an equal number of values from upper and lower ends of a sorted dataset. Winsorizing is similar but doesn’t remove values. Instead, it replaces them with the closest original value not affected by the process. Tukey’s FUNOR-FUNOM offers an alternate approach. The procedure’s name reflects its purpose: FUNOR-FUNOM uses FUNOP to identify outliers, and then uses separate *rejection* and *modification* procedures to treat them. The technique offers a number of innovations. First, unlike trimming and Winsorizing, which affect all the values at the top and bottom ends of a sorted dataset, FUNOR-FUNOM uses FUNOP to *identify* individual outliers to treat. Second, FUNOR-FUNOM leverages statistical properties of the dataset to determine *individual* modifications for those outliers. FUNOR-FUNOM is specifically designed to operate on two-way (or contingency) tables. Similar to other techniques that operate on contingency tables, it uses the table’s grand mean (*x~..~*) and the row and column means (*x~j.~* and *x~.k~*, respectively) to calculate expected values for entries in the table. The equation below shows how these effects are combined. Because it’s unlikely for expected values to match the table’s actual values exactly, the equation includes a residual term (*y~jk~*) to account for any deviation. $$ \begin{align} (actual \space value) &= (general \space \mathit{effect}) + (row \space \mathit{effect}) + (column \space \mathit{effect}) + (deviation)\\ x_{jk} &= (x_{..}) + (x_{j.} - x_{..}) + (x_{.k} - x_{..}) + (y_{jk})\\ &= x_{..} + x_{j.} - x_{..} + x_{.k} - x_{..} + y_{jk}\\ &= x_{j.} + x_{.k} - x_{..} + y_{jk} \end{align} $$ FUNOR-FUNOM is primarily interested in the values that deviate most from their expected values, the ones with the largest residuals. So, to calculate residuals, simply swap the above equation around: $$ y_{jk}=x_{jk}-x_{j.}-\ x_{.k}+\ x_{..}\ $$ FUNOR-FUNOM starts by repeatedly applying FUNOP, looking for outlier residuals. When it finds them, it modifies the outlier with the greatest deviation by applying the following modification: $$ x_{jk}\rightarrow x_{jk}-{\Delta x}_{jk} $$ where $$ \Delta x_{jk}=\ z_{jk} \cdot a_{a(n)}\cdot\frac{r\cdot c}{\left(r-1\right)\left(c-1\right)} $$ Recalling the definition of slope (from FUNOP) $$ z_i=\frac{y_i - \acute{y}}{a_{i|n}} $$ the first portion of the Δ*x~jk~* equation reduces to just *y~jk~* – *y̍*, the difference of the residual from the median. The second portion of the equation is a factor, based solely upon table size, meant to compensate for the effect of an outlier on the table’s grand, row, and column means. When Δ*x~jk~* is applied to the original value, the *y~jk~* terms cancel out, effectively setting the outlier to its expected value (based upon the combined effects of the contingency table) plus a factor of the median residual (~ *x~j.~* + *x~.k~* + *x~..~* + *y̍*). FUNOR-FUNOM repeats this same process until it no longer finds values that “deserve special attention.” In the final phase, the FUNOM phase, the procedure uses a lower threshold of interest---FUNOP with a lower *A*---to identify a final set of outliers for treatment. The adjustment becomes $$ \Delta x_{jk} = (z_{jk} - B_M \cdot z̍)a_{i|n} $$ There are a couple of changes here. First, the inclusion of (–*B~M~* · *z̍*) effectively sets the residual of outliers to FUNOP’s threshold of interest, much like the way that Winsorizing sets affected values to the same cut-off threshold. FUNOM, though, sets *only the residual* of affected values to that threshold: The greater part of the value is determined by the combined effects of the grand, row, and column means. Second, because we’ve already taken care of the largest outliers (whose adjustment would have a more significant effect on the table’s means), we no longer need the compensating factor. The chart below shows the result of applying FUNOR-FUNOM to the data in Table 2 of Tukey’s paper. ```{r echo = FALSE, fig.width = 7, fig.height = 4} # cleanse the table cleansed_t2 <- funor_funom(table_2) data.frame( i = 1:length(table_2), original = as.vector(table_2), cleansed = as.vector(cleansed_t2) ) %>% ggplot(aes(x = i)) + geom_point(aes(y = original), color = 'black') + geom_segment(aes( x = i, y = original, xend = i, yend = cleansed ), color = 'black', linetype = 'dashed') + geom_point(aes(y = cleansed), color = 'grey') + labs(title = 'Changes to Table 2', y = 'value', x = '') ``` The grey dots represent the cleansed dataset. The black dots represent the values of affected points *prior* to treatment, and the dashed lines connect those points to their treated values, illustrating the extent to which those points changed. FUNOR handles the largest adjustments, which Tukey accomplishes by setting *A~R~* = 10 and *B~R~* = 1.5 for that portion of the process, and FUNOP handles the finer adjustments by setting *A~M~* = 0 and *B~M~* = 1.5. Again, because the procedure leverages the statistical properties of the data, each of the resulting adjustments is unique. Here's an example on a smaller dataset. ```{r} # create a random dataset, representing a two-way table set.seed(42) dat <- matrix(rnorm(16), nrow = 4) # add some noise dat[2, 1] <- rnorm(1, mean = 10) # cleanse the table of outliers cleansed_dat <- funor_funom(dat) # look at the two tables, before and after dat cleansed_dat # look at the difference between the two tables # only one non-zero difference dat - cleansed_dat ``` ### Vacuum cleaner FUNOR-FUNOM treats the outliers of a contingency table by identifying and minimizing outsized residuals, based upon the grand, row, and column means. Tukey takes these concepts further with his vacuum cleaner, whose output is a set of residuals, which can be used to better understand sources of variance in the data and enable more informed analysis. To isolate residuals, Tukey’s vacuum cleaner uses regression to break down the values from the contingency table into their constituent components (p 51): $$ \mathit{ (original \space values) = (dual \space regression) \\ + (deviations \space \mathit{of} \space row \space regression \space \mathit{from} \space dual \space regression) \\ + (deviations \space \mathit{of} \space column \space regression \space \mathit{from} \space dual \space regression) \\ + (residuals) \\ } $$ The idea is very similar to the one based upon the grand, row, and column means. In fact, the first stage of the vacuum cleaner produces the same result as subtracting the combined effect of the means from the original values. To do this, the vacuum cleaner needs to calculate regression coefficients for each row and column based upon the values in our table (*y~rc~*) and a carrier---or regressor---for both rows (*a~r~*) and columns (*b~c~*). Below is the equation used to calculate regression coefficients for columns. $$ [y/a]_c= \frac{\sum_r{a_ry_{rc}}}{\sum_r a_r^2} $$ Conveniently, the equation will give us the mean of a column when we set ar ≡ 1: $$ [y/a]_c= \frac{\sum_r{1 \cdot y_{rc}}}{\sum_r 1} = \frac{\sum_r{y_{rc}}}{n_r} $$ where *n~r~* is the number of rows. Effectively, the equation iterates through every row (Σ*~r~*), summing up the individual values in the same column (*c*) and dividing by the number of rows, the same as calculating the mean (*y~.c~*). Note, however, that *a~r~* is a vector. So to set *a~r~* ≡ 1, we need our vector to satisfy this equation: $$ \sum_r a_r^2=1 $$ For a vector of length *n~r~* we can simply assign every member the same value: $$ \sqrt{\frac{1}{n_r}} $$ Our initial regressors end up being two sets of vectors, one for rows and one for columns, containing either √(1/*n~c~*) for rows or √(1/*n~r~*) for columns. Finally, in the same way that the mean of all row means or the mean of all column means can be used to calculate the grand mean, either the row coefficients or column coefficients can be used to calculate a dual-regression (or “grand”) coefficient: $$ \frac{\sum_{c}{\left[y/a\right]_cb_c}}{\sum_{c} b_c^2}\ \equiv\ \frac{\sum\sum{a_ry_{rc}b_c}}{\sum\sum{a_r^2b_c^2}}\equiv\frac{\sum_{r}{a_r\left[y/b\right]_r}}{\sum_{r} a_r^2}\ =\ \left[y/ab\right]\ $$ The reason for calculating all of these coefficients, rather than simply subtracting the grand, row, and column means from our table’s original values, is that Tukey’s vacuum cleaner reuses the coefficients from this stage as regressors in the next. (To ensure *a~r~* ≡ 1 and *a~c~* ≡ 1 for the next stage, we normalize both sets of new regressors.) The second phase is the real innovation. Tukey takes one of his earlier ideas, one degree of freedom for non-additivity, and applies it separately to each row and column. This, Tukey tells us, “…extracts row-by-row regression upon ‘column mean minus grand mean’ and column-by-column regression on ‘row mean minus grand mean’” (p 53). The result is a set of residuals, vacuum cleaned of systemic effects. ``` {r} # convert the output of vacuum_cleaner into a long data frame dat <- vacuum_cleaner(table_8) %>% as.data.frame() %>% dplyr::mutate('row' = dplyr::row_number()) %>% tidyr::pivot_longer(cols = dplyr::starts_with('V'), names_to = 'col', values_to = 'value') # since the table_8 was a two-way table, the rows are factors dat$row <- as.factor(dat$row) # conduct analysis of variance aov_results <- aov(value ~ row + col, dat) summary(aov_results) ``` ### Data sets and errata There are three data sets in this package, which Tukey provided, one for each procedure. * **Table 1** contains example data for FUNOP (p 24) * **Table 2** is a 36 x 15 two-way table and contains example data for FUNOR-FUNOM (p 26) * **Table 8** is a 36 x 15 two-way table and contains example data for the vacuum cleaner (p 54). Note that Tukey's published table contains a typo, which has been corrected in this package. (See note below) "The Future of Data Analysis" contains a handful of errors that can make a detailed investigation of the paper difficult. Below, I've documented what I found in case anyone wants to dig more deeply themselves: * One of Tukey's Gaussian calculations contains an arithmetic error: *a*~4|14~ should be Gau^-1^(11/43) (p 23) * As mentioned, one of the values in Table 8 has an inverted sign: the value in row 23, column 10 should be 0.100, not -0.100 (p 54) * The numerator for [y/ab], when based up the row coefficent, should be Σ*~r~* *a~r~*[*y/**b***]*~r~* instead of Σ*~r~* *a~r~*[*y/**a***]*~r~* (p 52) * Tukey swaps two values in when he plugs them into a key regression equation: 0.258 and 0.167 (p 55). The equation should read: $$ 0.126 - (0.014)(0.167) - (-0.459)(0.258) - (0.921)(0.258)(0.167) \space \doteq \space 0.20 $$ ### References Tukey, John W. "The Future of Data Analysis." *The Annals of Mathematical* Statistics, *33*(1), 1962, pp 1-67. *JSTOR*, <https://www.jstor.org/stable/2237638>.
/scratch/gouwar.j/cran-all/cranData/vacuum/inst/doc/vacuum-vignette.Rmd
--- title: "Vacuum Vignette" author: "Ron Sielinski" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Vacuum Vignette} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup, include = FALSE} library(vacuum) library(ggplot2) library(magrittr) library(tidyr) library(dplyr) ``` ## A tidy implementation of John Tukey's vacuum cleaner One of John Tukey’s landmark papers, “The Future of Data Analysis” [1], contains a set of analytical procedures that focus on the analysis of two-way (contingency) tables. **Vacuum** contains an implementation of the three procedures: * FUNOP (**FU**ll **NO**rmal **P**lot): Identifies outliers within a vector by calculating the slope (*z*) of every element, relative to the vector's median. * FUNOR-FUNOM (**FU**ll **NO**rmal **R**ejection-**FU**ll **NO**rmal **M**odification): Treats a two-way (contingency) table for outliers by isolating residuals from the table's likely systemic effects, which are calculated from the table's grand, row, and column means. * Vacuum cleaner: Removes systemic effects from values in a two-way table, returning a set of residuals that can be used for further examination (e.g., analysis of variance). ### FUNOP The base prodecure is FUNOP, which identifies outliers in a vector. Here’s Tukey’s definition: >(b1) Let *a~i|n~* be a typical value for the *i*th ordered observation in a sample of *n* from a unit normal distribution. >(b2) Let *y*~1~ ≤ *y*~2~ ≤ … ≤ *y*~n~ be the ordered values to be examined. Let *y̍* be their median (or let *y̆*, read “y trimmed”, be the mean of the *y~i~* with \frac{1}{3}*n* < *i* ≤ \frac{1}{3}(2*n*). >(b3) For *i* ≤ ⅓*n* or > ⅓(2*n*) only, let *z~i~* = (*y~i~* – *y̍*)/*a~i|n~* (or let *z~i~* = (*y~i~* – *y̆*) /*a~i|n~*). >(b4) Let *z̍* be the median of the *z*’s thus obtained (about \frac{1}{3}(2*n*) in number). >(b5) Give special attention to *z*’s for which both |*y~i~* – *y̍*| ≥ A · *z̍* and *z~i~* ≥ B · *z̍* where A and B are prechosen. >(b5*) Particularly for small *n*, *z~j~*’s with *j* more extreme than an *i* for which (b5) selects *z~i~* also deserve special attention… (p 23). The basic idea is very similar to a Q-Q plot. Tukey gives us a sample of 14 data points. On a normal Q-Q plot, if data are normally distributed, they form a straight line. But in the chart below, based upon data from Tukey’s example, we can clearly see that a couple of the points are relatively distant from the straight line. They’re outliers. ```{r echo = FALSE, fig.width = 7, fig.height = 4} # Normal Q-Q plot for Tukey's sample data data.frame(y = table_1) %>% ggplot(aes(sample = y)) + stat_qq() + stat_qq_line() + #geom_abline(aes(intercept = 0, slope = 1)) + labs(title = 'Normal Q-Q plot of sample data') ``` The goal of FUNOP, though, is to eliminate the need for visual inspection by automating interpretation. The first variable in the FUNOP procedure (*a~i|n~*) simply gives us the theoretical distribution, where *i* is the ordinal position in the range 1..*n* and Gau^-1^ is the quantile function of the normal distribution (i.e., the “Q” in Q-Q plot): $$ a_{i|n}=\ {\rm Gau}^{-1}\left[\frac{\left(3i-1\right)}{\left(3n+1\right)}\right] $$ The key innovation of FUNOP is to calculate the slope of each point, relative to the median. ``` {r echo = FALSE, fig.width = 7, fig.height = 4} x <- table_1 n <- length(x) y_split <- median(x) dat <- data.frame(i = 1:n, y_sorted = sort(x), a = a_qnorm(1:n, n), z = (sort(x) - y_split) / a_qnorm(1:n, n) ) # find the point with the greatest slope key_pt <- dat[which.max(dat$z), ] # plot the points and the slope of the point key point ggplot(dat, aes(x = a, y = y_sorted)) + geom_point(color = 'darkgrey') + geom_point(dat = key_pt, aes(x = a, y = y_sorted), color = 'black') + geom_point(aes(x = 0, y = y_split), color = 'red') + # example line geom_segment(aes(x = 0, y = y_split, xend = key_pt$a, yend = key_pt$y_sorted)) + labs(title = 'Sorted values of y plotted against theoretical distribution a(y)', y = 'y') ``` If *y̍* is the median of the sample, and we presume that it’s located at the midpoint of the distribution (where *a*(*y*) = 0), then the slope of each point can be calculated as: $$ z_i=\frac{y_i - \acute{y}}{a_{i|n}} $$ The chart above illustrates how slope of one point (1.2, 454) is calculated, relative to the median (0, 33.5). $$ z\ =\ \frac{\Delta y}{\Delta a}\ =\ \frac{\left(454.0-\ 33.5\right)}{\left(1.2-0\right)}=350.4 $$ Any point that has a slope significantly steeper than the rest of the population is necessarily farther from the straight line. To do this, FUNOP simply compares each slope (*z~i~*) to the median of all *calculated* slopes (*z̍*). Note, however, that FUNOP calculates slopes for the top and bottom thirds of the sorted population only, in part because *z~i~* won’t vary much over the inner third, but also because the value of *a~i|n~* for the inner third will be close to 0 and dividing by ≈0 when calculating *z~i~* might lead to instability. Significance---what Tukey calls “special attention”---is partially determined by *B*, one of two predetermined values (or hyperparameters). For his example, Tukey recommends a value between 1.5 and 2.0, which means that FUNOP simply checks whether the slope of any point, relative to the midpoint, is 1.5 or 2.0 times larger than the median. The other predetermined value is *A*, which is roughly equivalent to the number of standard deviations of *y~i~* from *y̍* and serves as a second criterion for significance. The following chart shows how FUNOP works. ``` {r echo = FALSE, , fig.width = 7, fig.height = 4} A <- 0 B <- 1.5 tmp <- funop(table_1, A, B) # need z & special for every point tmp$z <- (tmp$y - median(tmp$y)) / a_qnorm(tmp$i, n) tmp$special[is.na(tmp$special)] <- FALSE # need outer to get special and outer to add up as a factor tmp$outer <- !tmp$middle z_split <- attr(tmp, 'z_split') y_split <- attr(tmp, 'y_split') extreme_B <- B * z_split extreme_A <- A * z_split ggplot(tmp, aes(x = y, y = z)) + geom_point(aes(color = as.factor(outer + special))) + geom_hline(yintercept = z_split) + geom_hline(yintercept = extreme_B, color = 'blue', alpha = 0.5) + geom_vline(xintercept = y_split, color = 'green3', alpha = 0.75) + geom_rect( xmin = -Inf, xmax = Inf, ymin = extreme_B, ymax = Inf, alpha = 0.0075, fill = 'blue' ) + geom_rect( xmin = y_split - extreme_A, xmax = y_split + extreme_A, ymin = -Inf, ymax = Inf, alpha = 0.01, fill = 'green' ) + labs(title = 'FUNOP: slope (z) plotted against original values') + labs(x = 'original values') + scale_color_manual( name = 'values', labels = c( 'excluded', 'undistinguished', 'special attention' ), values = c('green3', 'black', 'red') ) ``` Our original values are plotted along the *x*-axis. The points in the green make up the inner third of our sample, and we use them to calculate *y̍*, the median of just those points, indicated by the green vertical line. The points not in green make up the outer thirds (i.e., the top and bottom thirds) of our sample, and we use them to calculate *z̍*, the median slope of just those points, indicated by the black horizontal line. Our first selection criterion is *z~i~* ≥ *B* · *z̍*. In his example, Tukey sets *B* = 1.5, so our threshold of interest is 1.5*z̍*, indicated by the blue horizontal line. We’ll consider any point above that line (the shaded blue region) to “deserve special attention”. We have only one such point, colored red. Our second criterion is |*y~i~* – *y̍*| ≥ *A* · *z̍*. In his example, Tukey sets *A* = 0, so our threshold of interest is |*y~i~* – *y̍*| ≥ 0 or (more simply) *y~i~* ≠ *y̍*. Basically, any point not on the green line. Our one point in the shaded blue region isn’t on the green line, so we still have our one point. Our final criterion is any *z~j~*’s with *j* more extreme than any *i* selected so far. Basically, that’s any value more extreme than the ones already identified. In this case, we have one value that’s larger (further to the right on the *x*-axis) than our red dot. That point is also colored red, and we flag it as deserving special attention. The two points identified by FUNOP are the same ones that we identified visually in Chart 1. ```{r} # Table 1 contains example data from Tukey's paper table_1 result <- funop(table_1) result # value of the outliers result[which(result$special == TRUE), 'y'] ``` ### FUNOR-FUNOM A common reason for identifing outliers is to do something about them, often by trimming or Winsorizing the dataset. The former simply removes an equal number of values from upper and lower ends of a sorted dataset. Winsorizing is similar but doesn’t remove values. Instead, it replaces them with the closest original value not affected by the process. Tukey’s FUNOR-FUNOM offers an alternate approach. The procedure’s name reflects its purpose: FUNOR-FUNOM uses FUNOP to identify outliers, and then uses separate *rejection* and *modification* procedures to treat them. The technique offers a number of innovations. First, unlike trimming and Winsorizing, which affect all the values at the top and bottom ends of a sorted dataset, FUNOR-FUNOM uses FUNOP to *identify* individual outliers to treat. Second, FUNOR-FUNOM leverages statistical properties of the dataset to determine *individual* modifications for those outliers. FUNOR-FUNOM is specifically designed to operate on two-way (or contingency) tables. Similar to other techniques that operate on contingency tables, it uses the table’s grand mean (*x~..~*) and the row and column means (*x~j.~* and *x~.k~*, respectively) to calculate expected values for entries in the table. The equation below shows how these effects are combined. Because it’s unlikely for expected values to match the table’s actual values exactly, the equation includes a residual term (*y~jk~*) to account for any deviation. $$ \begin{align} (actual \space value) &= (general \space \mathit{effect}) + (row \space \mathit{effect}) + (column \space \mathit{effect}) + (deviation)\\ x_{jk} &= (x_{..}) + (x_{j.} - x_{..}) + (x_{.k} - x_{..}) + (y_{jk})\\ &= x_{..} + x_{j.} - x_{..} + x_{.k} - x_{..} + y_{jk}\\ &= x_{j.} + x_{.k} - x_{..} + y_{jk} \end{align} $$ FUNOR-FUNOM is primarily interested in the values that deviate most from their expected values, the ones with the largest residuals. So, to calculate residuals, simply swap the above equation around: $$ y_{jk}=x_{jk}-x_{j.}-\ x_{.k}+\ x_{..}\ $$ FUNOR-FUNOM starts by repeatedly applying FUNOP, looking for outlier residuals. When it finds them, it modifies the outlier with the greatest deviation by applying the following modification: $$ x_{jk}\rightarrow x_{jk}-{\Delta x}_{jk} $$ where $$ \Delta x_{jk}=\ z_{jk} \cdot a_{a(n)}\cdot\frac{r\cdot c}{\left(r-1\right)\left(c-1\right)} $$ Recalling the definition of slope (from FUNOP) $$ z_i=\frac{y_i - \acute{y}}{a_{i|n}} $$ the first portion of the Δ*x~jk~* equation reduces to just *y~jk~* – *y̍*, the difference of the residual from the median. The second portion of the equation is a factor, based solely upon table size, meant to compensate for the effect of an outlier on the table’s grand, row, and column means. When Δ*x~jk~* is applied to the original value, the *y~jk~* terms cancel out, effectively setting the outlier to its expected value (based upon the combined effects of the contingency table) plus a factor of the median residual (~ *x~j.~* + *x~.k~* + *x~..~* + *y̍*). FUNOR-FUNOM repeats this same process until it no longer finds values that “deserve special attention.” In the final phase, the FUNOM phase, the procedure uses a lower threshold of interest---FUNOP with a lower *A*---to identify a final set of outliers for treatment. The adjustment becomes $$ \Delta x_{jk} = (z_{jk} - B_M \cdot z̍)a_{i|n} $$ There are a couple of changes here. First, the inclusion of (–*B~M~* · *z̍*) effectively sets the residual of outliers to FUNOP’s threshold of interest, much like the way that Winsorizing sets affected values to the same cut-off threshold. FUNOM, though, sets *only the residual* of affected values to that threshold: The greater part of the value is determined by the combined effects of the grand, row, and column means. Second, because we’ve already taken care of the largest outliers (whose adjustment would have a more significant effect on the table’s means), we no longer need the compensating factor. The chart below shows the result of applying FUNOR-FUNOM to the data in Table 2 of Tukey’s paper. ```{r echo = FALSE, fig.width = 7, fig.height = 4} # cleanse the table cleansed_t2 <- funor_funom(table_2) data.frame( i = 1:length(table_2), original = as.vector(table_2), cleansed = as.vector(cleansed_t2) ) %>% ggplot(aes(x = i)) + geom_point(aes(y = original), color = 'black') + geom_segment(aes( x = i, y = original, xend = i, yend = cleansed ), color = 'black', linetype = 'dashed') + geom_point(aes(y = cleansed), color = 'grey') + labs(title = 'Changes to Table 2', y = 'value', x = '') ``` The grey dots represent the cleansed dataset. The black dots represent the values of affected points *prior* to treatment, and the dashed lines connect those points to their treated values, illustrating the extent to which those points changed. FUNOR handles the largest adjustments, which Tukey accomplishes by setting *A~R~* = 10 and *B~R~* = 1.5 for that portion of the process, and FUNOP handles the finer adjustments by setting *A~M~* = 0 and *B~M~* = 1.5. Again, because the procedure leverages the statistical properties of the data, each of the resulting adjustments is unique. Here's an example on a smaller dataset. ```{r} # create a random dataset, representing a two-way table set.seed(42) dat <- matrix(rnorm(16), nrow = 4) # add some noise dat[2, 1] <- rnorm(1, mean = 10) # cleanse the table of outliers cleansed_dat <- funor_funom(dat) # look at the two tables, before and after dat cleansed_dat # look at the difference between the two tables # only one non-zero difference dat - cleansed_dat ``` ### Vacuum cleaner FUNOR-FUNOM treats the outliers of a contingency table by identifying and minimizing outsized residuals, based upon the grand, row, and column means. Tukey takes these concepts further with his vacuum cleaner, whose output is a set of residuals, which can be used to better understand sources of variance in the data and enable more informed analysis. To isolate residuals, Tukey’s vacuum cleaner uses regression to break down the values from the contingency table into their constituent components (p 51): $$ \mathit{ (original \space values) = (dual \space regression) \\ + (deviations \space \mathit{of} \space row \space regression \space \mathit{from} \space dual \space regression) \\ + (deviations \space \mathit{of} \space column \space regression \space \mathit{from} \space dual \space regression) \\ + (residuals) \\ } $$ The idea is very similar to the one based upon the grand, row, and column means. In fact, the first stage of the vacuum cleaner produces the same result as subtracting the combined effect of the means from the original values. To do this, the vacuum cleaner needs to calculate regression coefficients for each row and column based upon the values in our table (*y~rc~*) and a carrier---or regressor---for both rows (*a~r~*) and columns (*b~c~*). Below is the equation used to calculate regression coefficients for columns. $$ [y/a]_c= \frac{\sum_r{a_ry_{rc}}}{\sum_r a_r^2} $$ Conveniently, the equation will give us the mean of a column when we set ar ≡ 1: $$ [y/a]_c= \frac{\sum_r{1 \cdot y_{rc}}}{\sum_r 1} = \frac{\sum_r{y_{rc}}}{n_r} $$ where *n~r~* is the number of rows. Effectively, the equation iterates through every row (Σ*~r~*), summing up the individual values in the same column (*c*) and dividing by the number of rows, the same as calculating the mean (*y~.c~*). Note, however, that *a~r~* is a vector. So to set *a~r~* ≡ 1, we need our vector to satisfy this equation: $$ \sum_r a_r^2=1 $$ For a vector of length *n~r~* we can simply assign every member the same value: $$ \sqrt{\frac{1}{n_r}} $$ Our initial regressors end up being two sets of vectors, one for rows and one for columns, containing either √(1/*n~c~*) for rows or √(1/*n~r~*) for columns. Finally, in the same way that the mean of all row means or the mean of all column means can be used to calculate the grand mean, either the row coefficients or column coefficients can be used to calculate a dual-regression (or “grand”) coefficient: $$ \frac{\sum_{c}{\left[y/a\right]_cb_c}}{\sum_{c} b_c^2}\ \equiv\ \frac{\sum\sum{a_ry_{rc}b_c}}{\sum\sum{a_r^2b_c^2}}\equiv\frac{\sum_{r}{a_r\left[y/b\right]_r}}{\sum_{r} a_r^2}\ =\ \left[y/ab\right]\ $$ The reason for calculating all of these coefficients, rather than simply subtracting the grand, row, and column means from our table’s original values, is that Tukey’s vacuum cleaner reuses the coefficients from this stage as regressors in the next. (To ensure *a~r~* ≡ 1 and *a~c~* ≡ 1 for the next stage, we normalize both sets of new regressors.) The second phase is the real innovation. Tukey takes one of his earlier ideas, one degree of freedom for non-additivity, and applies it separately to each row and column. This, Tukey tells us, “…extracts row-by-row regression upon ‘column mean minus grand mean’ and column-by-column regression on ‘row mean minus grand mean’” (p 53). The result is a set of residuals, vacuum cleaned of systemic effects. ``` {r} # convert the output of vacuum_cleaner into a long data frame dat <- vacuum_cleaner(table_8) %>% as.data.frame() %>% dplyr::mutate('row' = dplyr::row_number()) %>% tidyr::pivot_longer(cols = dplyr::starts_with('V'), names_to = 'col', values_to = 'value') # since the table_8 was a two-way table, the rows are factors dat$row <- as.factor(dat$row) # conduct analysis of variance aov_results <- aov(value ~ row + col, dat) summary(aov_results) ``` ### Data sets and errata There are three data sets in this package, which Tukey provided, one for each procedure. * **Table 1** contains example data for FUNOP (p 24) * **Table 2** is a 36 x 15 two-way table and contains example data for FUNOR-FUNOM (p 26) * **Table 8** is a 36 x 15 two-way table and contains example data for the vacuum cleaner (p 54). Note that Tukey's published table contains a typo, which has been corrected in this package. (See note below) "The Future of Data Analysis" contains a handful of errors that can make a detailed investigation of the paper difficult. Below, I've documented what I found in case anyone wants to dig more deeply themselves: * One of Tukey's Gaussian calculations contains an arithmetic error: *a*~4|14~ should be Gau^-1^(11/43) (p 23) * As mentioned, one of the values in Table 8 has an inverted sign: the value in row 23, column 10 should be 0.100, not -0.100 (p 54) * The numerator for [y/ab], when based up the row coefficent, should be Σ*~r~* *a~r~*[*y/**b***]*~r~* instead of Σ*~r~* *a~r~*[*y/**a***]*~r~* (p 52) * Tukey swaps two values in when he plugs them into a key regression equation: 0.258 and 0.167 (p 55). The equation should read: $$ 0.126 - (0.014)(0.167) - (-0.459)(0.258) - (0.921)(0.258)(0.167) \space \doteq \space 0.20 $$ ### References Tukey, John W. "The Future of Data Analysis." *The Annals of Mathematical* Statistics, *33*(1), 1962, pp 1-67. *JSTOR*, <https://www.jstor.org/stable/2237638>.
/scratch/gouwar.j/cran-all/cranData/vacuum/vignettes/vacuum-vignette.Rmd
utils::globalVariables(c("incl_nt", "neu_set", "rm_qm"))
/scratch/gouwar.j/cran-all/cranData/vader/R/globals.R
#' Get a dataframe of vader results for multiple text documents #' #' Use vader_df() to calculate the valence of multiple texts contained within a vector or column in a dataframe. #' #' @param text to be analyzed; for vader_df(), the text should be a single vector (e.g. 1 column) #' @param incl_nt defaults to T, indicates whether you wish to incl UNUSUAL n't contractions (e.g., yesn't) in negation analysis #' @param neu_set defaults to T, indicates whether you wish to count neutral words in calculations #' @param rm_qm defaults to T, indicates whether you wish to clean quotation marks from text (setting to F may result in errors) #' @importFrom tm stopwords #' @return A dataframe containing the valence score for each word; an overall, compound valence score for the text; the weighted percentage of positive, negative, and neutral words in the text; and the frequency of the word "but". #' @examples #' vader_df(c("I'm happy", "I'm yesn't happy")) #' vader_df(c("I'm happy", "I'm yesn't happy"), incl_nt = FALSE) #' vader_df(c("I'm happy", "I'm yesn't happy"), neu_set = FALSE) #' vader_df(c("I said \"I'm not happy\", "I said \" I'm not happy \" "), rm_qm = FALSE) #' #' @export #' #' @section N.B.: #' In the examples below, "yesn't" is an internet neologism meaning "no", "maybe yes, maybe no", "didn't", etc. #' #' @seealso \code{\link{get_vader}} to get vader results for a single text document vader_df <- function(text, incl_nt = T, neu_set = T, rm_qm = F){ # Unlisting in case tibble text <- unlist(text) df <- lapply(text, function(x) data.frame(as.list(get_vader(x, incl_nt, neu_set, rm_qm)))) df <- do.call("rbind", df) df <- cbind(text, df) # Changing Factors to Numeric (Must Convert to Character 1st) df[ , -c(1:2)] <- sapply(df[ , -c(1:2)], as.character) df[ , -c(1:2)] <- sapply(df[ , -c(1:2)], as.numeric) # Warnings err <- length(which(df$word_scores == "ERROR")) if(err == 1 ) warning("1 row contains an error. Filter word_scores for 'ERROR' to identify the problematic text.") if(err > 1 ) warning(paste(err, "rows contain an error. Filter word_scores for 'ERROR' to identify the problematic text.")) return(df) }
/scratch/gouwar.j/cran-all/cranData/vader/R/vader_df.R
#' Get a named vector of vader results for a single text document #' #' Use get_vader() to calculate the valence of a single text document. #' #' @param text to be analyzed; for get_vader(), the text should be a character string #' @param incl_nt defaults to T, indicates whether you wish to incl UNUSUAL n't contractions (e.g., yesn't) in negation analysis #' @param neu_set defaults to T, indicates whether you wish to count neutral words in calculations #' @param rm_qm defaults to T, indicates whether you wish to clean quotation marks from text (setting to F may result in errors) #' @importFrom tm stopwords #' @return A named vector containing the valence score for each word; an overall, compound valence score for the text; the weighted percentage of positive, negative, and neutral words in the text; and the frequency of the word "but". #' @examples #' get_vader("I yesn't like it") #' get_vader("I yesn't like it", incl_nt = FALSE) #' get_vader("I yesn't like it", neu_set = FALSE) #' get_vader("I said \"I'm not happy\"", rm_qm = FALSE) #' get_vader("I said \" I'm not happy \" ", rm_qm = FALSE) #' #' @export #' #' @seealso \code{\link{vader_df}} to get vader results for multiple text documents #' #' @section References: #' #' For the original Python Code, please see: #' \itemize{ #' \item https://github.com/cjhutto/vaderSentiment #' \item https://github.com/cjhutto/vaderSentiment/blob/master/vaderSentiment/vaderSentiment.py #' } #' #' For the original R Code, please see: #' \itemize{ #' \item https://github.com/nrguimaraes/sentimentSetsR/blob/master/R/ruleBasedSentimentFunctions.R #' } #' #' Modifications to the above scripts include, but are not limited to: #' #' \itemize{ #' \item ALL CAPS fx: updated to account for non-alpha words; i.e. "I'M 100 PERCENT SURE" would previously have been counted as mixed case due to the use of numbers #' \item IDIOMS fx: added capacity to check for idioms that do not contain any words found in the Vader Lexicon #' \item WORDS+EMOT: strip punctuation while preserving ALL emoticons found in dictionary #' \item Option to turn on/off neutral count #' } #' #' @section N.B.: #' In the examples below, "yesn't" is an internet neologism meaning "no", "maybe yes, maybe no", "didn't", etc. get_vader <- function(text, incl_nt = T, neu_set = T, rm_qm = T){ tryCatch({ # are 'nt contractions included in negation calculation (if not in negation constants) incl_nt <<- incl_nt # are neutral words counted neu_set <<- neu_set # converts text to UTF-8 encoding text <- iconv(text, to="UTF-8") # remove quotation marks from text if(rm_qm == T) {text <- gsub('"', '', text)} # checks if supplied text is empty if(!grepl("[[:graph:]]", text)) { return(c(word_scores = NA, compound = NA, pos = NA, neu = NA, neg = NA, but_count = NA)) } else { #returns score to user return(polarity_scores(text))} }, error=function(e){c(word_scores = "ERROR", compound = NA, pos = NA, neu = NA, neg = NA, but_count = NA)}) }
/scratch/gouwar.j/cran-all/cranData/vader/R/vader_main_call.R
# prepare text to analyze by stripping leading and trailing punctuation # preserves contractions and all emoticons found in vader dictionary strip_punc <- function(wpe) { for(i in 1:length(wpe)){ #checks if word is emoticon found in vader lexicon if(!(tolower(wpe[i]) %in% vaderLexicon$V1)) { #if not, strip punctuation leadingAndTrailing <- "(^\\W+)|(\\W+$)" wpe[i] <- gsub(leadingAndTrailing, "", wpe[i]) } } return(wpe) } wordsPlusEmo <- function(text) { #splits text into vector of words wpe <- unlist(strsplit(text, "\\s+")) #strips words of punctuation (unless the word is an emoticon) stripped <- strip_punc(wpe) return(stripped) }
/scratch/gouwar.j/cran-all/cranData/vader/R/vader_prep_text.R
#calculate sentiment score # check for modification in sentiment due to contrastive conjunction "but" but_check <- function(wpe, sentiments){ but_index <- NULL if("but" %in% tolower(wpe)){ but_index <- which(tolower(wpe) == "but") for (s in seq_along(sentiments)) { if (s < but_index[1]) {sentiments[s] <- sentiments[s] * 0.5} # else if (s > but_index[1] && s < but_index[length(but_index)]) {sentiments[s] <- sentiments[s] * 0.75} else if (s > but_index[1]) {sentiments[s] <- sentiments[s] * 1.5} } } results <- list(sentiments = sentiments, but_count = length(but_index)) return(results) } # Normalize the score to be between -1 and 1 using an alpha that approximates the max expected value normalize <- function(score, alpha=15) { norm_score = score / sqrt((score * score) + alpha) if(norm_score < (-1.0)) {return(-1.0)} else if(norm_score > 1.0) {return(1.0)} else {return(norm_score)} } # count frequency of character in text count_char <- function(my_char, text){ char_count <- 0 char_look <- unlist(gregexpr(my_char, text)) if(any(char_look != -1)){ char_count <- length(char_look) } return(char_count) } # count frequency of ! in text and assign appropriate scaling p_amp <- function(text){ p_count <- count_char("!", text) if(p_count > 4) {p_count <- 4} amp_p <- p_count * 0.292 return(amp_p) } # count frequency of ? in text and assign appropriate scaling qm_amp <- function(text){ qm_count <- count_char("\\?", text) amp_qm <- 0 if(qm_count > 1) { if(qm_count <= 3) {amp_qm <- qm_count * 0.18} else(amp_qm <- 0.96) } return(amp_qm) } # add emphasis from exclamation points and question marks pq_amp <- function(text) { amp_p <- p_amp(text) amp_qm <- qm_amp(text) amp_pqm <- amp_p + amp_qm return(amp_pqm) } # create positive, negative, and neutral sentiment scores sift_senti_scores <- function(score){ pos_sum <- 0 neu_sum <- 0 neg_sum <- 0 for(s in score){ # 1 is added/subtracted based on Vader Python Script if(s > 0) {pos_sum <- pos_sum + s + 1} if(s < 0) {neg_sum <- neg_sum + s - 1} if(s == 0) {neu_sum <- neu_sum + 1} } return(c(pos_sum = pos_sum, neu_sum = neu_sum, neg_sum = neg_sum)) } # calculate (adjusted) percentage of text that are positive, negative, or neutral total_senti_scores <- function(pos_sum, neu_sum, neg_sum){ total <- pos_sum + abs(neg_sum) + neu_sum pos <- pos_sum / total neg <- abs(neg_sum) / total neu <- neu_sum / total return(c(pos_total = pos, neu_total = neu, neg_total = neg)) } # calculate compound score after factoring in added emphasis for exclamation points and question marks compound_calc <- function(sentiments, text, punc_amp){ sum_s <- sum(sentiments, na.rm = T) if(sum_s > 0) {sum_s <- sum_s + punc_amp} else if(sum_s < 0) {sum_s <- sum_s - punc_amp} compound <- normalize(sum_s) return(compound) } score_val <- function(sentiments, text){ punc_amp <- 0 punc_amp <- pq_amp(text) compound <- 0 scores_total <- c(pos_total = 0, neu_total = 0, neg_total = 0) if(any(!is.na(sentiments))) { compound <- compound_calc(sentiments, text, punc_amp) # if text contains more positive words, increase positive score depending on punctuation marks # if text contains more negative words, decrease negative score depending on punctuation marks scores_dif <- sift_senti_scores(sentiments[!is.na(sentiments)]) if(scores_dif["pos_sum"] > abs(scores_dif["neg_sum"])) {scores_dif["pos_sum"] <- scores_dif["pos_sum"] + punc_amp} else if(scores_dif["pos_sum"] < abs(scores_dif["neg_sum"])) {scores_dif["neg_sum"] <- scores_dif["neg_sum"] - punc_amp} # create vector positive, negative, and neutral words scores_total <- total_senti_scores(scores_dif["pos_sum"], scores_dif["neu_sum"], scores_dif["neg_sum"]) names(scores_total) <- c("pos", "neu", "neg") } # return compound and indivdiual (positive, negative, neutral) sentiment scores results <- c(compound = compound, scores_total) results <- round(results, digits = 3) return(results) }
/scratch/gouwar.j/cran-all/cranData/vader/R/vader_sentiment_score.R