Skip to content

Instantly share code, notes, and snippets.

@tomsing1
Last active December 9, 2025 22:32
Show Gist options
  • Select an option

  • Save tomsing1/fabbfdc443251f70ad9bec0c723ab05e to your computer and use it in GitHub Desktop.

Select an option

Save tomsing1/fabbfdc443251f70ad9bec0c723ab05e to your computer and use it in GitHub Desktop.
Replace missing values in a matrix with 1/2 of the minimum value of each row (in R)
library(checkmate)
# Replace missing values in a matrix with 1/2 of the minimum value of each row
m <- matrix(1:9, ncol = 3)
m[1, 3] <- NA
m[3, 1] <- NA
m
impute_half_minimum <- function(m, verbose = TRUE) {
checkmate::assert_matrix(m)
checkmate::assert_flag(verbose)
na_positions <- is.na(m)
if (any(na_positions)) {
replacement_val <- apply(m, 1, min, na.rm = TRUE) / 2
# rows without valid values yield an Inf replacement_val, reset those to NA
replacement_val[!is.finite(replacement_val)] <- NA
# look up the replacement value for each row
insert_val <- replacement_val[row(m)[na_positions]]
# if there are any valid replacement values, insert them
n_valid_insert_val <- sum(!is.na(insert_val))
if (isTRUE(verbose) & n_valid_insert_val > 0) {
message("Replacing ", n_valid_insert_val, " missing measurements",
" with 50% of the smallest observed value for that row." )
}
m[na_positions] <- insert_val
}
return(m)
}
n <- impute_half_minimum(m)
stopifnot(n[1, 3] == 0.5)
stopifnot(n[3, 1] == 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment