local({ previous_options <- options(warn = 2, digits = 8, stringsAsFactors = FALSE) on.exit(options(previous_options), add = TRUE) check_counts <- function(x, allow_missing = FALSE, allow_empty = FALSE) { if (!(is.integer(x) || is.double(x)) || is.object(x) || !is.null(dim(x))) { stop("Use a plain numeric vector") } if (length(x) > 256L || (!allow_empty && length(x) == 0L)) { stop("Use 1..256 counts unless empty input is explicitly allowed") } if (any(is.nan(x)) || (!allow_missing && anyNA(x))) { stop("Missing or undefined counts are not allowed here") } observed <- x[!is.na(x)] if (any(!is.finite(observed)) || any(observed < 0) || any(observed > 1000000) || any(observed != floor(observed))) { stop("Counts must be finite whole numbers from 0 to 1000000") } invisible(x) } validate_sessions <- function(data) { if (!is.data.frame(data) || !identical(names(data), c("id", "room", "visits"))) { stop("Expected id, room and visits columns") } if (!is.character(data$id) || !is.character(data$room) || anyNA(data$id) || anyNA(data$room) || any(!nzchar(trimws(data$id))) || any(!nzchar(trimws(data$room))) || anyDuplicated(data$id)) { stop("Use unique ids and non-empty room labels") } check_counts(data$visits, allow_missing = TRUE) invisible(data) } sessions <- data.frame(id = c("S1", "S2"), room = c("East", "West"), visits = c(8, NA_real_)) validate_sessions(sessions) cat("valid rows:", nrow(sessions), "unknown counts:", sum(is.na(sessions$visits)), "\n") invisible(NULL) })