socialresearchcentre / projectable

Produce table-like objects made up of special metadata-rich column vectors, and project them into two dimensions.
https://socialresearchcentre.github.io/projectable
GNU General Public License v3.0
3 stars 0 forks source link

col_median #13

Open kinto-b opened 4 years ago

kinto-b commented 4 years ago

Implement a col_median to supplement col_freq and col_binomial

kinto-b commented 3 years ago

What fields should belong to a col_median? Obviously median, but other than that?

kinto-b commented 2 years ago

In GOS-L we need at least the N count. In some cases we also need bootstrapped confidence intervals:

sd_boot <- function(x) {
  if (length(x)==0) return(NA)
  set.seed(322)
  sd(boot(x, function(x, w, ...) median(x[w], ...), 1000, na.rm = TRUE)$t)
}

col_median <- function(x) {
  n <- length(x)
  med <- median(x, na.rm = TRUE)

  projectable::new_col(
    median = med,
    N = n,
    class = "median" 
  )
}

col_median_ci <- function(x, ci_error = 0.1) {
  n <- length(x)
  med <- NA_real_
  lcl <- NA_real_
  ucl <- NA_real_

  if (n!=0) {
    med <- median(x, na.rm = TRUE)
    stddev <- sd_boot(x)
    conf <- 1-ci_error
    lcl <- (med - qt(conf + ci_error/2, n - 1) * stddev)
    ucl <- (med + qt(conf + ci_error/2, n - 1) * stddev)
  }

  projectable::new_col(
    median = med,
    N = n,
    ci_error = ci_error,
    ci_lower = lcl,
    ci_upper = ucl,
    class = "median_ci"
  )
}