Keep row order constant in ci function
Change-Id: I46f6509a1f4b3defb62ef8c42653f6e1f76e10be
diff --git a/R/ci.R b/R/ci.R
index fcb05e8..032b677 100644
--- a/R/ci.R
+++ b/R/ci.R
@@ -20,7 +20,9 @@
#' @export
#' @importFrom stats prop.test
#' @importFrom tibble remove_rownames
-#' @importFrom dplyr enquo rename starts_with
+#' @importFrom dplyr enquo rename starts_with filter mutate rowwise bind_rows select arrange row_number quo_name
+#' @importFrom broom tidy
+#' @importFrom tidyr unnest
#' @examples
#' \dontrun{
#'
@@ -39,27 +41,48 @@
conf.level = 0.95) {
x <- enquo(x)
N <- enquo(N)
- nas <- df %>%
- dplyr::filter(is.na(total) | total <= 0) %>%
- mutate(f = NA, conf.low = NA, conf.high = NA)
-
- if (nrow(df) == nrow(nas))
- return(nas)
-
- df %>%
- dplyr::filter(total > 0) %>%
- rowwise %>%
- mutate(tst = list(
- broom::tidy(prop.test(!!x,!!N, conf.level = conf.level)) %>%
- select(estimate, conf.low, conf.high) %>%
- rename(f = estimate)
- )) %>%
- tidyr::unnest(tst) %>%
- bind_rows(nas)
+
+ # Add row index to preserve original order
+ df <- df %>% mutate(.row_index = row_number())
+
+ # Initialize result with all NA values
+ result <- df %>%
+ mutate(f = NA_real_, conf.low = NA_real_, conf.high = NA_real_)
+
+ # Calculate confidence intervals for valid rows
+ # Use the column names from the enquoted expressions
+ N_col <- quo_name(N)
+ x_col <- quo_name(x)
+ valid_indices <- which(df[[N_col]] > 0 & !is.na(df[[N_col]]) & !is.na(df[[x_col]]))
+
+ if (length(valid_indices) > 0) {
+ valid_data <- df[valid_indices, ]
+
+ ci_results <- valid_data %>%
+ rowwise %>%
+ mutate(tst = list(
+ broom::tidy(prop.test(!!x, !!N, conf.level = conf.level)) %>%
+ select(estimate, conf.low, conf.high) %>%
+ rename(f = estimate)
+ )) %>%
+ tidyr::unnest(tst) %>%
+ select(.row_index, f, conf.low, conf.high)
+
+ # Update result with calculated values
+ for (i in seq_len(nrow(ci_results))) {
+ row_idx <- ci_results$.row_index[i]
+ result$f[row_idx] <- ci_results$f[i]
+ result$conf.low[row_idx] <- ci_results$conf.low[i]
+ result$conf.high[row_idx] <- ci_results$conf.high[i]
+ }
+ }
+
+ # Remove the helper column
+ result %>% select(-.row_index)
}
## Mute notes: "Undefined global functions or variables:"
-globalVariables(c("totalResults", "total", "estimate", "tst"))
+globalVariables(c("totalResults", "total", "estimate", "tst", ".row_index", "f", "conf.low", "conf.high", "N_col", "x_col"))
# ci.old <- function(df, x = totalResults, N = total, conf.level = 0.95) {