R Programming / Language and data foundations / Lesson 7
Summarize missing observations explicitly
Count observed and missing values before computing a mean and define behavior when every value is missing.
On this page
Lesson goals
- Distinguish missing values from numeric zero.
- Compute a mean over observed values with an explicit denominator.
- Define and test the all-missing case.
- Define the observed denominator and reconcile missing counts with input.
- Distinguish empty, all-missing and zero cases and NA from nonfinite values.
Define what is being summarized
A missing observation is not automatically zero. Replacing NA with zero changes both the total and the meaning of the average unless zero is an intentional domain value. Decide which rows represent the population, how missing values should be reported, and whether an observed-only mean answers the question. The examples use three synthetic measurements and do not claim that removing missingness removes bias.
Count and sum observed values
The first block builds a logical mask with is.na, counts the observed entries, and sums those entries. For c(2, NA, 4), the observed count is two and the total is six. Reporting the missing count alongside the mean makes the denominator visible. This example assumes a numeric vector; validate input type and any domain-specific range before treating external data as measurements.
values <- c(2, NA, 4)
observed <- !is.na(values)
count <- sum(observed)
total <- sum(values[observed])
count
total
The mask excludes NA while keeping genuine zero values as observations.
Handle the empty denominator
The function in the second block selects observed values, returns NA_real_ if none remain, and otherwise divides their sum by their count. The first call gives a mean of three; the second represents an undefined observed-only mean rather than inventing zero. The two blocks are independent. A real analysis should document why the all-missing result is missing and how later reporting will display it.
mean_observed <- function(x) {
observed <- x[!is.na(x)]
if (length(observed) == 0) return(NA_real_)
sum(observed) / length(observed)
}
mean_observed(c(2, NA, 4))
mean_observed(c(NA_real_, NA_real_))
The explicit length check avoids dividing by an empty observed set.
Interpret the result carefully
An observed-only mean describes the values that were observed. If missing values are related to the measurement itself or to another characteristic, it may not represent the complete population. Investigate the missingness pattern and document any assumption before comparing groups. A missing-value policy is an analytical decision, not just a switch that suppresses warnings. Keep the original data available for review.
Verify boundary cases
Test a complete vector, a mix of values and NA, an all-missing vector, an empty vector, and a vector containing a valid zero. Confirm count, total, and mean against hand calculations. Check that zero remains an observed value and that the all-missing and empty cases follow the documented policy. If external inputs can contain NaN or nonnumeric values, define and test their handling separately.
Define the unit and observed denominator
A missing-observation summary begins with a target population, measurement unit, period, and eligibility rule. The length of a vector counts supplied entries, not necessarily eligible people or valid measurements. For a numeric vector with a declared one-entry-per-eligible-record contract, classify each entry as observed or missing, keep the original count, and state whether the desired mean is over observed values or the full eligible population. An observed-only mean describes the observed subset; it does not reveal the missing values or establish that their distribution matches the observed values.
For `c(4,NA,8)`, the observed values total 12 and number two, so their mean is 6; the vector contains three entries and one missing value. Report all three quantities rather than only the mean. A measured zero is observed and contributes to both sum and denominator. Treating NA as zero changes the question: the same vector would become 4,0,8 and average 4. Keep a stable ID when values correspond to people or events so exclusions can be traced and repeated observations are not mistaken for independent entities.
Build and reconcile an explicit mask
For an ordinary numeric vector, `!is.na(x)` identifies entries that are not NA or NaN. Use that mask consistently for the sum and the observed count: `sum(x[observed])` and `sum(observed)` refer to the same selected entries. Verify the invariant observed count plus missing count equals total length when those categories are exhaustive and mutually exclusive. If a mask is generated separately, check its length and identity alignment; logical recycling or reordered records can select the wrong values even when a result looks plausible.
Comparisons involving NA can themselves be NA. Selecting with an unguarded logical mask containing NA can preserve unknown result entries rather than simply dropping them. For an observed-positive rule, `!is.na(x) & x>0` explicitly excludes missing entries because FALSE AND an unknown comparison is FALSE. Count known nonpositive values separately from missing values to avoid describing an unknown measurement as a failed threshold. A selection policy is an analytical decision: if missingness is related to the outcome, excluding it can change the population represented by the summary.
Define empty and all-missing behavior
An empty input and an all-missing input both have zero observed values, but they differ in how many records were supplied. Under a function contract returning `NA_real_` when no observations remain, `numeric(0)` gives total length zero and missing count zero, while `c(NA_real_,NA_real_)` has total length two and missing count two. In both cases the observed-only mean is unavailable. State that policy explicitly rather than returning zero merely because an empty sum is zero. A valid observed vector `c(0,0)` has observed count two and mean zero, so it must remain distinguishable from the two no-mean cases.
Base R's `mean(x,na.rm=TRUE)` on an all-missing numeric vector can yield `NaN` after removal; a wrapper can deliberately return `NA_real_` instead when that is the documented interface. The wrapper should validate its inputs and return or report total, observed and missing counts along with the value so callers can distinguish why no mean exists. Tests should cover complete, partially missing, all-missing, empty and genuine-zero fixtures. These cases validate the stated rule only; they cannot demonstrate that a real source is representative.
Define numeric and nonfinite policies separately
`is.na()` identifies both NA and NaN for ordinary numeric vectors, but Inf is not missing. `is.finite()` is false for NA, NaN, Inf and -Inf. An observed-only rule based only on `!is.na` can therefore retain an infinite value; a finite-measurement contract needs an additional finiteness rule. Distinguish a missing category from a rejected nonfinite value when those reasons matter. For `c(2,NA,NaN,Inf)`, the missing test marks two entries, while the finite test retains only 2. Do not call the other three failures all the same thing without declaring that classification.
Character text `"NA"` is not the same R value as `NA_character_` unless an import policy converts it. A malformed text token can become newly missing during conversion; retain the original token and report new conversion failures separately from source missingness. A nonnumeric vector should be rejected or parsed under a documented rule before a numeric summary, rather than coerced silently into a believable result. Numeric type and finiteness checks do not prove the values have the correct units or that the selection process is unbiased.
Compare alternatives and qualify verification
A sensitivity comparison shows how an explicit policy changes the result. For values 2, NA and 10, observed-only mean is 6 from two values; zero-filling gives 4 from three. The calculation does not say which policy is correct: that depends on what NA means and the decision context. When comparing groups, show each group's total, observed and missing counts and its own denominator. Different missing rates can make observed-only means incomparable even if the code is internally consistent. Describe whether follow-up, data quality review, or additional assumptions could address the gap.
These examples use synthetic inputs and base R. The authoring environment has no R or Rscript executable, so snippets and custom outputs are derived expectations marked non-runnable; no R parsing or execution is claimed. A later compatible clean-session run should record the R version, compare actual values, types, counts and warnings, and check the function's empty and invalid-input behavior. A passing fixture supports the tested contract, not population representativeness or a causal interpretation. Preserve raw data and the chosen missingness policy so another analyst can explain why the denominator changed.
20 worked examples
1. Complete numeric vector
Problem: Find the observed count, total and mean.
- All three values are observed and their sum is 18.
- The mean is 18/3=6 and no entry is missing.
x <- c(3,6,9)
observed <- !is.na(x)
count <- sum(observed)
total <- sum(x[observed])
All three values are observed and their sum is 18. The mean is 18/3=6 and no entry is missing.
Expected result: count 3; total 18; mean 6; missing 0
Why this result follows: The numerator and denominator use the same observed values.
2. Valid zero and missing value
Problem: Which values enter the observed mean?
- Zero is nonmissing, while the second entry is NA.
- The selected values 0 and 8 total 8 and average 4 over two observations.
x <- c(0,NA_real_,8)
observed <- !is.na(x)
selected <- x[observed]
Zero is nonmissing, while the second entry is NA. The selected values 0 and 8 total 8 and average 4 over two observations.
Expected result: Selected 0,8; count 2; mean 4
Why this result follows: A genuine zero remains in both numerator and denominator.
3. Two missing records
Problem: Reconcile all four entries and calculate the mean.
- The mask identifies 5 and 7 as observed and two entries as missing.
- Their sum is 12, so the observed mean is 12/2=6; 2+2=4 records.
x <- c(NA_real_,5,NA_real_,7)
observed <- !is.na(x)
The mask identifies 5 and 7 as observed and two entries as missing. Their sum is 12, so the observed mean is 12/2=6; 2+2=4 records.
Expected result: observed 2; missing 2; mean 6
Why this result follows: The missing and observed categories partition the input.
4. The wrong denominator
Problem: Compare the two proposed averages.
- The observed total 12 divided by the original length 3 gives 4.
- Dividing the same total by two observed values gives 6; the first ratio effectively treats the missing entry as zero.
x <- c(2,NA_real_,10)
observed_sum <- 12
incorrect_divisor <- length(x)
correct_divisor <- sum(!is.na(x))
The observed total 12 divided by the original length 3 gives 4. Dividing the same total by two observed values gives 6; the first ratio effectively treats the missing entry as zero.
Expected result: Original-length ratio 4; observed mean 6
Why this result follows: A numerator excluding missingness requires the matching observed denominator.
5. Zero fill changes the target
Problem: Compare the two stated policies.
- Removing NA uses 2 and 10, giving mean 6.
- Replacing it with zero uses three values totaling 12, giving mean 4; the policy difference is substantive.
x <- c(2,NA_real_,10)
observed_mean <- mean(x,na.rm=TRUE)
filled_mean <- mean(c(2,0,10))
Removing NA uses 2 and 10, giving mean 6. Replacing it with zero uses three values totaling 12, giving mean 4; the policy difference is substantive.
Expected result: Observed mean 6; zero-filled mean 4
Why this result follows: A missing-value assumption changes the data being summarized.
6. Empty input under a wrapper policy
Problem: What counts and mean state should be reported?
- The input has zero entries and therefore zero observed and missing entries.
- The stated wrapper returns NA_real_ because there is no observed denominator.
x <- numeric(0)
observed <- x[!is.na(x)]
# contract: return NA_real_ when length(observed)==0
The input has zero entries and therefore zero observed and missing entries. The stated wrapper returns NA_real_ because there is no observed denominator.
Expected result: total 0; observed 0; missing 0; mean NA_real_
Why this result follows: An empty input has no observed mean under this contract.
7. All missing under the same policy
Problem: How does this differ from an empty input?
- Two records were supplied and both are missing, so observed length is zero.
- The wrapper returns NA_real_, but total 2 and missing 2 distinguish this case from empty input.
x <- c(NA_real_,NA_real_)
observed <- x[!is.na(x)]
# contract: return NA_real_ when length(observed)==0
Two records were supplied and both are missing, so observed length is zero. The wrapper returns NA_real_, but total 2 and missing 2 distinguish this case from empty input.
Expected result: total 2; observed 0; missing 2; mean NA_real_
Why this result follows: The same unavailable mean can arise from different input histories.
8. A genuine zero mean
Problem: Why is zero a valid mean here?
- Both supplied values are observed numeric zeros.
- Their sum is zero and count is two, so the mean is a valid 0, not an unavailable result.
x <- c(0,0)
observed <- x[!is.na(x)]
value <- mean(observed)
Both supplied values are observed numeric zeros. Their sum is zero and count is two, so the mean is a valid 0, not an unavailable result.
Expected result: total 2; observed 2; missing 0; mean 0
Why this result follows: An observed zero denominator contribution differs from no observation.
9. Missing test and NaN
Problem: Compare missing and finite masks.
- is.na flags the second and third entries: NA and NaN.
- is.finite flags only 2 as finite; Inf is not missing but is nonfinite.
x <- c(2,NA_real_,NaN,Inf)
missing <- is.na(x)
finite <- is.finite(x)
is.na flags the second and third entries: NA and NaN. is.finite flags only 2 as finite; Inf is not missing but is nonfinite.
Expected result: is.na: F,T,T,F; is.finite: T,F,F,F
Why this result follows: Missingness and finiteness tests classify different conditions.
10. A finite-only policy
Problem: What remains for a finite-only mean?
- Only 2 passes is.finite; NA, NaN and Inf do not.
- The retained count is one and mean is 2, under the explicitly finite-only rule.
x <- c(2,NA_real_,NaN,Inf)
finite_values <- x[is.finite(x)]
Only 2 passes is.finite; NA, NaN and Inf do not. The retained count is one and mean is 2, under the explicitly finite-only rule.
Expected result: Finite count 1; mean 2
Why this result follows: A stricter finite policy excludes more than missing values alone.
11. Text NA is a label
Problem: Which position is missing before a custom import policy?
- The first token is literal text "NA", and the third is "ok".
- Only the second is the missing character value, giving mask FALSE,TRUE,FALSE.
x <- c("NA",NA_character_,"ok")
missing <- is.na(x)
The first token is literal text "NA", and the third is "ok". Only the second is the missing character value, giving mask FALSE,TRUE,FALSE.
Expected result: Missing mask FALSE,TRUE,FALSE
Why this result follows: A quoted token is not automatically the R missing value.
12. Unknown comparison in selection
Problem: What does direct selection contain?
- The comparison gives FALSE,NA,TRUE.
- Indexing by that mask retains an unknown entry and the value 5, so the result has two entries.
x <- c(1,NA_real_,5)
mask <- x > 2
y <- x[mask]
The comparison gives FALSE,NA,TRUE. Indexing by that mask retains an unknown entry and the value 5, so the result has two entries.
Expected result: mask FALSE,NA,TRUE; selected NA,5
Why this result follows: An NA logical index is not automatically dropped.
13. Observed threshold policy
Problem: Which value is selected under this policy?
- The observed check is TRUE,FALSE,TRUE; the threshold comparison is FALSE,NA,TRUE.
- Their AND is FALSE,FALSE,TRUE, selecting 5 only and excluding the missing entry by policy.
x <- c(1,NA_real_,5)
mask <- !is.na(x) & x > 2
y <- x[mask]
The observed check is TRUE,FALSE,TRUE; the threshold comparison is FALSE,NA,TRUE. Their AND is FALSE,FALSE,TRUE, selecting 5 only and excluding the missing entry by policy.
Expected result: mask FALSE,FALSE,TRUE; selected 5
Why this result follows: A false observed check resolves the missing mask position.
14. Counts after threshold filtering
Problem: Reconcile selected, known failing, and missing IDs.
- C=4 is positive and selected; A=0 and D=-1 are observed but fail.
- B is missing, giving 1 selected + 2 known failing + 1 missing = 4 input records.
x <- c(A=0,B=NA,C=4,D=-1)
rule: observed and greater than 0
C=4 is positive and selected; A=0 and D=-1 are observed but fail. B is missing, giving 1 selected + 2 known failing + 1 missing = 4 input records.
Expected result: selected C; known failing A,D; missing B
Why this result follows: Separate reasons prevent an unknown from being reported as a known failure.
15. Group-specific missingness
Problem: Compare means and observed coverage.
- A has 2 observed of 4 with mean (2+4)/2=3.
- B has 4 observed of 4 with mean (3+5+7+9)/4=6; different coverage limits comparison.
group A: values [2,4,NA,NA]
group B: values [3,5,7,9]
rule: observed-only mean
A has 2 observed of 4 with mean (2+4)/2=3. B has 4 observed of 4 with mean (3+5+7+9)/4=6; different coverage limits comparison.
Expected result: A mean 3, observed 2/4; B mean 6, observed 4/4
Why this result follows: Group denominators reveal unequal missingness behind the summaries.
16. Missing can change a conclusion
Problem: Compare full-three-value means under the scenarios.
- Scenario A gives (4+6+0)/3=10/3β3.33.
- Scenario B gives (4+6+20)/3=10; neither assumed value is an observed measurement.
observed: [4,6]
missing: 1
scenario A assumes missing value 0
scenario B assumes missing value 20
Scenario A gives (4+6+0)/3=10/3β3.33. Scenario B gives (4+6+20)/3=10; neither assumed value is an observed measurement.
Expected result: A mean 10/3β3.33; B mean 10
Why this result follows: Sensitivity scenarios reveal how unobserved values can change the result.
17. Conversion failure versus source missing
Problem: How many missing values are original and newly introduced?
- The original NA_character_ is one source missing value.
- The invalid token bad becomes another NA with warning expected; the converted vector has two missing values.
raw <- c("2","bad",NA_character_)
converted <- as.numeric(raw)
The original NA_character_ is one source missing value. The invalid token bad becomes another NA with warning expected; the converted vector has two missing values.
Expected result: Original missing 1; new conversion failure 1; total missing 2
Why this result follows: Preserving raw tokens separates absence from a parsing failure.
18. A raw input remains available
Problem: What information is retained for later review?
- The derived observed vector contains 2 and 4 and mean is 3.
- The original x still contains three entries including NA, allowing the missing count and selection policy to be reviewed.
x <- c(2,NA_real_,4)
observed <- x[!is.na(x)]
result <- mean(observed)
The derived observed vector contains 2 and 4 and mean is 3. The original x still contains three entries including NA, allowing the missing count and selection policy to be reviewed.
Expected result: raw length 3; observed length 2; mean 3
Why this result follows: Separate names preserve the original input and derived subset.
19. An invalid input type
Problem: Does this input satisfy the numeric contract?
- The supplied object is character, not a numeric vector.
- Reject or explicitly parse under a documented policy before summarizing; do not treat the invalid token as a zero measurement.
x <- c("2","bad")
contract: nonempty finite numeric vector
proposed action: calculate mean directly
The supplied object is character, not a numeric vector. Reject or explicitly parse under a documented policy before summarizing; do not treat the invalid token as a zero measurement.
Expected result: Contract fails: character input
Why this result follows: Type validation precedes a numeric summary.
20. Composable summary state
Problem: Return sum, observed count and missing count for combining a chunk later.
- The observed values 2 and 6 sum to 8 and have count 2.
- The remaining entry is missing, so its count is 1 and it does not enter the sum.
x <- c(2,NA_real_,6)
observed <- x[!is.na(x)]
list(observed_sum=sum(observed),observed_count=length(observed),missing_count=sum(is.na(x)))
The observed values 2 and 6 sum to 8 and have count 2. The remaining entry is missing, so its count is 1 and it does not enter the sum.
Expected result: observed_sum=8, observed_count=2, missing_count=1.
Why this result follows: Keeping sum and count permits correctly weighted combination with another chunk.
Common errors and fixes
The mean is artificially lowered
- Why it happens
- Missing values were replaced with zero without a domain justification.
- How to fix it
- Keep missingness distinct and choose a documented summary policy.
- Prevent it next time
- Report observed and missing counts with the estimate.
The denominator includes missing values
- Why it happens
- The total excluded NA but the divisor used the original vector length.
- How to fix it
- Divide by the number of observed values.
- Prevent it next time
- Test a small vector with a hand-calculated mean.
An all-missing group is reported as zero
- Why it happens
- An empty observed set was given an arbitrary numeric default.
- How to fix it
- Return a documented missing result or handle the group explicitly.
- Prevent it next time
- Include all-missing and empty groups in tests.
20 practice exercises
1. What are the observed count and mean for c(2, NA, 4)?
Show hint
Count only nonmissing entries for the observed mean.
Show worked solution
There are two observed values, totaling six, so the observed-only mean is three. One value is missing and should be reported separately rather than counted as zero.
The observed values are 2 and 4, so the count is 2, total is 6 and mean is 6/2=3. One of the three entries is missing; do not add it to the denominator as zero.
Check your solution
- Observed count is 2 and total is 6.
- Observed mean is 3 and missing count is 1.
2. What happens when every measurement is NA?
Show hint
Trace the explicit zero-observation branch in the original function.
Show worked solution
The function returns NA_real_ because no observed denominator exists. A report can label the estimate unavailable and show the missing count rather than inventing a zero mean.
When all measurements are NA, the observed subset has length zero. The original wrapper returns NA_real_ instead of dividing by zero or inventing mean zero. A report should distinguish this two-record all-missing case from a genuinely empty input and a valid zero mean.
Check your solution
- Observed count is 0.
- The original wrapper returns NA_real_ for the all-missing input.
3. Two observed values are 4 and 6 and one missing value is known only to lie in [0,10]. Bound the full three-record mean.
Show hint
Use the smallest and largest permitted missing value.
Show worked solution
The total lies between 10 and 20, so the full mean lies between 10/3 and 20/3. These are sensitivity bounds under the stated range, not an observed mean.
Check your solution
- The lower bound is 10/3.
- The upper bound is 20/3.
4. Compare the missing fraction for an empty vector and for two missing entries. What special status is needed?
Show hint
A fraction requires a nonzero total count.
Show worked solution
The all-missing vector has missing fraction 2/2=1. For the empty vector the denominator is zero, so return a documented no-records status rather than a numeric fraction.
Check your solution
- The all-missing fraction is 1.
- The empty fraction is undefined.
5. Values 2 and 4 are observed and one value is missing. Apply a documented observed-mean imputation and report the new total.
Show hint
Compute the observed mean before filling.
Show worked solution
The observed mean is 3, so mean imputation produces 2,4,3 with total 9. Label the filled value as imputed; this assumption does not turn it into an observed measurement.
Check your solution
- The imputed value is 3.
- The filled total is 9.
6. A short logical mask c(TRUE,FALSE) is applied to x=c(A=1,B=2,C=3,D=4). Predict the base-vector selection, then design a guard for one flag per record.
Show hint
The short mask can recycle across the four entries.
Show worked solution
Ordinary vector indexing recycles the mask to TRUE,FALSE,TRUE,FALSE and selects A and C. If the analysis contract requires one independently supplied flag per record, reject the length-two mask with a length check before selection and validate ID alignment.
Check your solution
- The base selection is A and C.
- A strict one-flag-per-record guard rejects length 2 for 4 records.
7. A finite-only summary checks all(is.finite(numeric(0))) and gets TRUE. Why is a separate count check required?
Show hint
An all check can pass vacuously on empty input.
Show worked solution
The finiteness check is TRUE because there are no counterexamples, but the vector contains zero observations. Require a positive retained count or return an explicit no-data status before calculating a mean.
Check your solution
- The finite check passes vacuously.
- The retained count is zero.
8. A source uses -999 as a missing sentinel, but -999 is also a valid measurement in another dataset. What must the import contract specify?
Show hint
Token meaning depends on source and column.
Show worked solution
Declare the sentinel only for the source and column where it means missing, preserving raw values for review. Applying it globally could discard legitimate -999 observations elsewhere.
Check your solution
- The sentinel policy is source-specific.
- Legitimate -999 values are not removed globally.
9. A report says 80% of ten eligible records are observed, but its counts show seven observed and three missing. Diagnose coverage.
Show hint
Divide observed count by the eligible total.
Show worked solution
Observed coverage is 7/10=70%, not 80%. The counts reconcile to ten, so investigate the reported percentage or the population definition before publishing.
Check your solution
- Coverage is 70%.
- The reported 80% is inconsistent.
10. Chunk A contains values 2,NA,4 and chunk B contains 8,10. Combine observed sums and counts to get the overall observed mean; compare equal weighting of chunk means.
Show hint
Preserve valid count as well as each partial sum.
Show worked solution
A has sum 6 and observed count 2, mean 3; B has sum 18 and count 2, mean 9. The combined observed mean is 24/4=6, which equals the equal-chunk mean here only because the observed counts are equal. This equality need not hold for unequal counts.
Check your solution
- The combined sum is 24 and observed count 4.
- Both means equal 6 in this equal-count fixture.
11. Chunk A has a=2,b=4 and chunk B has b=4,c=8. Why does naive pooling double-count, and what is the unique-record mean?
Show hint
The repeated ID b represents the same record under the stated contract.
Show worked solution
Naive pooling counts b twice, giving 18/4=4.5. After verifying both b entries are the same record, the unique total is 14 over three IDs, giving 14/3; conflicting duplicates need a separate policy.
Check your solution
- The naive mean is 4.5.
- The unique-record mean is 14/3.
12. Group A has observed values 2 and 4 and two missing outcomes; B has complete values 3,5,7,9. Compare observed means, then calculate Aβs full mean if follow-up verifies the missing values as 12 and 14.
Show hint
Follow-up changes Aβs denominator from 2 to 4 while B stays fixed.
Show worked solution
Aβs observed-only mean is (2+4)/2=3 versus Bβs mean of 6. After verified follow-up, A has values 2,4,12,14 and mean 32/4=8, reversing the measured ordering. Report both snapshots and follow-up results; 12 and 14 cannot be assumed before observation.
Check your solution
- Aβs observed mean is 3 and Bβs mean is 6.
- Aβs follow-up full mean is 8, exceeding B.
13. A binary cohort has 20 eligible records, 6 observed successes, 4 observed failures and 10 missing. Compare the observed-only rate with full-cohort extreme bounds.
Show hint
For the bounds assign all missing outcomes to each extreme.
Show worked solution
The observed-only rate is 6/10=60%. Under known eligibility and binary outcomes, full-cohort bounds are 6/20=30% through 16/20=80%. The bounds describe missing completions, not a confidence interval or known full rate.
Check your solution
- The observed-only rate is 60%.
- The arithmetic bounds are 30%β80%.
14. A summary reports total=5, observed=3 and missing=3. Diagnose the count invariant and suggest a concrete investigation.
Show hint
Observed and missing are supposed to be disjoint and exhaustive.
Show worked solution
The stated categories sum to 3+3=6, exceeding total 5. Inspect whether a record was counted twice or categories were computed from different subsets, then reconcile IDs before calculating the mean. Do not repair the total by silently changing a count.
Check your solution
- Observed plus missing is 6, not 5.
- The counts must be reconciled before publication.
15. A two-record source has observed values 0 and 10. An analyst reports mean=5 and missing=1. Explain why at least one stated count or fixture value is inconsistent.
Show hint
Both supplied values are observed.
Show worked solution
The mean 5 is correct for 0 and 10, and observed count is 2. Under the stated two-record fixture missing count must be 0, not 1. Recheck the source or the report rather than changing the valid zero to missing.
Check your solution
- The observed mean is 5 from two values.
- The correct missing count for the fixture is 0.
16. A function returns mean=0 for both c(0,0) and c(NA,NA). Design a return contract that distinguishes the two cases.
Show hint
Include observed count and an unavailable state.
Show worked solution
Return mean 0 with observed=2 and missing=0 for c(0,0). For the all-missing vector return NA_real_ with observed=0 and missing=2 under the declared wrapper policy. Named fields prevent a valid zero from being confused with no observed mean.
Check your solution
- The zero vector has mean 0 and observed count 2.
- The all-missing vector has unavailable mean and missing count 2.
17. A numeric summary accepts NA but requires all observed values to be finite. Classify c(2,NA_real_,Inf) and explain why !is.na alone is insufficient.
Show hint
Inf is nonmissing but not finite.
Show worked solution
The missing mask marks NA only, so !is.na would retain 2 and Inf. Under the finite-observation contract, Inf must be rejected or separately classified; only 2 is both observed and finite. State whether the whole input fails or the nonfinite value is excluded.
Check your solution
- NA is missing and Inf is nonmissing but nonfinite.
- Only 2 is finite under the stated fixture.
18. An analyst removes missing values with na.rm=TRUE and claims this proves the average represents every eligible person. Identify the unsupported assumption and a useful follow-up.
Show hint
A computational option does not determine why values are missing.
Show worked solution
na.rm changes the calculation to observed values; it does not prove missing and observed people have the same outcome distribution. Report eligible, observed and missing counts, compare available characteristics, and seek follow-up or a justified sensitivity analysis without claiming those checks reveal unknown outcomes.
Check your solution
- The result is labeled observed-only.
- Missingness and possible selection differences are investigated.
19. A test plan for a missing-aware mean must cover a complete vector, an all-missing vector, an empty vector and a genuine zero. Supply four concrete inputs and expected mean states.
Show hint
Choose the policy for no observed values explicitly.
Show worked solution
Under a wrapper returning NA_real_ when no values remain, c(2,4) has mean 3; c(NA_real_) and numeric(0) have unavailable means; c(0) has valid mean 0. Check total and observed counts too, because the two unavailable cases have different input lengths.
Check your solution
- Complete input c(2,4) has mean 3; c(0) has mean 0.
- All-missing and empty inputs return NA_real_ but have different total counts.
20. A note says the missing-aware R function was verified, but the author had no R or Rscript and only hand calculations. Rewrite it and specify a later verification.
Show hint
Distinguish derived expectation from runtime evidence.
Show worked solution
State that expected counts and means were derived from synthetic inputs and documented rules, with no R parsing or execution in this environment. Later run the exact function in a compatible clean R session, recording version, types, results, warnings and boundary-case behavior.
Check your solution
- The revised note makes no R execution claim.
- The later run checks types, counts and boundary cases.
Key takeaways
- Keep missingness distinct from a valid zero.
- Report the denominator and define the all-missing outcome.
- An observed-only summary describes available values and does not reveal missing outcomes.
- A zero denominator needs an explicit policy, not an invented zero mean.
- Missingness and finiteness are different checks.