Skip to content

Commit

Permalink
implementation polishing
Browse files Browse the repository at this point in the history
  • Loading branch information
lhdjung committed Aug 24, 2023
1 parent 3a25886 commit 344c4ec
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
10 changes: 4 additions & 6 deletions R/median-possible.R
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,17 @@ median_range <- function(x) {
#' @export

median_possible_values.default <- function(x) {
# As in `median2.default()`:
n <- length(x)
x <- x[!is.na(x)]
nna <- n - length(x)
# Central index or indices in `x`; length 1 if the length of `x` is odd,
# length 2 if it is even:
half <- if (n %% 2L == 1L) {
(n + 1L) %/% 2L
} else {
(n + 1L:2L) %/% 2L
}
rm(n)
nna <- length(x[is.na(x)])
x <- sort(x[!is.na(x)])
# Some special rules:
# -- If all values are known, the only possible value is the actual one as
# -- If all values are known, the only possible median is the actual one as
# determined by `median2()`.
# -- If any central value is missing, there is no way to determine the
# possible median values.
Expand Down
3 changes: 2 additions & 1 deletion R/median2.R
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ median2.default <- function(x, na.rm = FALSE, ...) {
x <- x[!is.na(x)]
### START of new code
else if (anyNA(x)) {
# Using an `n` variable for consistency with the older code at the bottom:
n <- length(x)
# Central index or indices in `x`; length 1 if the length of `x` is odd,
# length 2 if it is even:
Expand All @@ -89,7 +90,7 @@ median2.default <- function(x, na.rm = FALSE, ...) {
x <- sort(x[!is.na(x)])
# Check for equality with offset value(s); see
# https://lhdjung.github.io/naidem/articles/algorithm.html for details:
if (!isTRUE(all(x[half] == x[half - nna]))) {
if (!isTRUE(all(x[half - nna] == x[half]))) {
return(x[NA_integer_])
} else if (length(half) == 2L) {
return(mean(x[half]))
Expand Down

0 comments on commit 344c4ec

Please sign in to comment.