R Programming Quiz: Stating Assumptions
10 questions · exam conditions
0:00
Stating AssumptionsQuestion 1 of 10

A CSV file contains a column named postal_code. Values such as 00123 and 02108 identify delivery regions. The current import step infers the column as integer, and blank fields become NA.

Which assumption should be stated before using postal_code to group deliveries?

postal_code is a character identifier, leading zeros are meaningful, and NA represents an unknown region rather than region zero.
postal_code is an integer measurement, leading zeros are formatting only, and NA may be replaced by the median observed code.
postal_code is an ordered numeric category, leading zeros are optional, and NA represents the lowest available delivery region.
postal_code is a numeric identifier, leading zeros can be restored later, and NA may be grouped with code 00000.
← Back to quizzes

R Programming Quiz

R Programming Quiz: Stating Assumptions

Practice Stating Assumptions in R Programming with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on Stating Assumptions, giving you a quick way to practice the rules, question types, and explanations that matter most for R Programming.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

All questions

Question 1

A CSV file contains a column named postal_code. Values such as 00123 and 02108 identify delivery regions. The current import step infers the column as integer, and blank fields become NA.

Which assumption should be stated before using postal_code to group deliveries?

  1. postal_code is a character identifier, leading zeros are meaningful, and NA represents an unknown region rather than region zero. (correct answer)
  2. postal_code is an integer measurement, leading zeros are formatting only, and NA may be replaced by the median observed code.
  3. postal_code is an ordered numeric category, leading zeros are optional, and NA represents the lowest available delivery region.
  4. postal_code is a numeric identifier, leading zeros can be restored later, and NA may be grouped with code 00000.
Explanation: Whenever you work with identifiers in R — things like postal codes, phone numbers, or ID numbers — the critical question is whether the values represent quantities or labels. This distinction drives every downstream decision about storage, transformation, and grouping. Postal codes are labels, not measurements. A code like 00123 has a meaningful leading zero: strip it and you get a completely different region. When R imports the column as integer, it silently drops that zero, turning 00123 into 123 — a data loss that corrupts your grouping. Before using the column, you must state that it should be stored as a character type, that leading zeros carry meaning, and that NA reflects a genuinely unknown region (not a stand-in for any real code). That's exactly what A captures, making it the correct answer. B is wrong on every clause: postal codes are not measurements, leading zeros are not "formatting only," and replacing NA with the median code is statistically nonsensical — you can't average region labels. C introduces the idea of an "ordered numeric category," but postal codes have no meaningful numeric order; a higher number doesn't mean a "greater" region. Treating NA as the lowest region fabricates data. D sounds cautious by suggesting zeros "can be restored later," but this is a false comfort — once R reads 00123 as integer 123, the original value is gone unless you re-import. Grouping NA with 00000 also invents a category without justification. Your study tip: whenever a column contains codes, IDs, or zip codes, always ask "is this a quantity or a label?" If it's a label, import it as character immediately — never plan to fix it after the fact.

Question 2

A weather station exports temperature in degrees Celsius. Its specification says that 999 indicates a disconnected probe and that a blank field indicates no transmission. The import uses read.csv(..., na.strings = c("", "999")).

Which documented assumption most adequately supports this treatment of missing values?

  1. Blank fields are missing, but 999 is a valid extreme temperature that should remain numeric for later range checking.
  2. Both encodings mean unavailable temperature, the station cannot legitimately report 999 degrees Celsius, and neither encoding means zero. (correct answer)
  3. 999 means unavailable temperature, while blank fields indicate a measured temperature of zero degrees Celsius.
  4. Both encodings mean unavailable temperature, but only after all readings have first been converted from Celsius to Fahrenheit.
Explanation: When working with na.strings in R, you're making a deliberate data documentation decision: you're asserting that certain values carry no meaningful measurement and should be treated as NA. The critical question is always what assumption justifies that assertion, and that assumption must be both domain-specific and complete. Both "" and "999" are mapped to NA by the import call, so the supporting assumption must explain why both encodings represent true unavailability — not a number, not zero, not a placeholder pending conversion. B does exactly this: it grounds the decision in the station's own specification (999°C is physically impossible as a real temperature report), confirms blank fields aren't zeroes, and treats both as genuinely missing. That's a fully documented, scientifically defensible assumption — making B correct. A fails because it argues 999 should stay numeric for range checking, which directly contradicts mapping it to NA. If you're passing 999 into na.strings, you've already discarded it — you can't have it both ways. C inverts the blank-field logic dangerously. Treating a blank as a zero-degree reading would silently inject false data into your analysis. Blanks indicate no transmission, not a measured zero. D introduces a red herring: unit conversion is completely irrelevant to whether a value is missing. The na.strings argument acts during import, before any transformation, and NA propagates through unit conversion regardless. A useful study habit: when you see na.strings, ask yourself "what documented, domain-specific fact justifies each value being declared missing?" The best answer is always the one that covers all encoded values with a coherent, real-world rationale.

Question 3

A vehicle file has numeric columns distance and elapsed. The device documentation says distance is recorded in meters and elapsed time in milliseconds. A failed timer is stored as NA; an elapsed value of zero can occur when the device malfunctions.

Which assumption statement best supports computing speed in meters per second?

  1. Distance is in meters, elapsed time is in milliseconds and must be divided by 1000, NA means unavailable, and zero elapsed time is invalid. (correct answer)
  2. Distance is in meters, elapsed time is already in seconds, NA means a stationary vehicle, and zero elapsed time produces zero speed.
  3. Distance is in kilometers, elapsed time is in milliseconds, NA means zero duration, and zero elapsed time may be retained as infinite speed.
  4. Distance and elapsed time share compatible units because both are numeric, NA may be ignored, and zero elapsed time needs no separate validation.
Explanation: When computing a derived quantity like speed, every assumption about your raw data must be grounded in the actual documentation — not guesses or convenient simplifications. Ask yourself: are the units correct, are missing values handled properly, and are edge cases (like division by zero) addressed? To compute speed in meters per second, you need distance in meters and elapsed time in seconds. Since the documentation states elapsed time is in milliseconds, you must convert: \text{elapsed_s} = \frac{\text{elapsed}}{1000}. You also need to exclude NA values (which signal unavailable timer readings) and reject zero elapsed times (which cause division by zero and represent device malfunctions, not real measurements). Answer A captures all of this precisely — correct units, proper conversion, appropriate NA semantics, and explicit zero-validation. Answer B fails because it claims elapsed time is already in seconds (contradicting the documentation) and misinterprets NA as "stationary vehicle" — an unsupported assumption that would silently corrupt your analysis. Answer C wrongly states distance is in kilometers and treats NA as zero duration, both of which contradict the documentation; it also suggests retaining infinite speed values, which is analytically dangerous. Answer D is the most subtly wrong: it assumes shared numeric type guarantees unit compatibility (it doesn't — type and unit are independent concepts), dismisses NA handling, and ignores zero-elapsed validation entirely. A useful study habit: whenever a question involves computing a derived variable in R, mentally check three things — unit conversion, NA handling, and boundary conditions. Missing any one of them can silently produce nonsensical results.

Question 4

A log contains local clock strings such as 2025-11-02 01:30, but it contains no UTC offset or time-zone column. An R script parses the strings with as.POSIXct() and computes elapsed time between events. The events occurred in a region that observes daylight-saving time.

Which assumption would make the elapsed-time calculation defensible without additional offset data?

  1. The strings represent UTC even though the source describes them as local times, and the computer's current time zone does not affect parsing.
  2. The strings are chronologically sorted, so any duplicated or nonexistent local clock times can be resolved from row order alone.
  3. The strings use the analyst's computer time zone, and daylight-saving transitions always preserve a one-to-one mapping to instants.
  4. The strings use one specified regional time zone, and the source guarantees that no event falls in a skipped or repeated local-time interval. (correct answer)
Explanation: Whenever you work with local timestamps in R, the core danger is ambiguity at DST boundaries: one local clock string can map to two real-world instants (during a "fall back" repeat), or zero instants (during a "spring forward" skip). Your elapsed-time calculation is only defensible if you can guarantee a clean one-to-one mapping between every string and a unique UTC instant. That's exactly what D provides. If the source specifies a single regional time zone and guarantees no event falls in a skipped or repeated interval, then as.POSIXct(x, tz = "America/Chicago") (or whichever zone applies) unambiguously converts every string to a UTC instant, and subtracting two instants gives correct elapsed time. Both conditions together close the loophole. A is wrong because it contradicts the premise — the passage explicitly calls these local times, not UTC. Claiming they're UTC doesn't make it so, and as.POSIXct() absolutely uses the computer's time zone when none is specified, so that second clause is also false. B is wrong because row order cannot resolve the ambiguity alone. During a "fall back," two consecutive rows could both show 01:30 representing instants one hour apart — or the reverse order. Sorting tells you sequence, not which UTC instant each string represents. C is wrong because DST transitions break the one-to-one mapping; that's the whole problem. Claiming transitions "always preserve" it is factually incorrect and the exact misconception this question is testing. Study tip: In R, always supply an explicit tz argument to as.POSIXct() for local timestamps, and never assume DST regions are safe without confirming no events land in transition windows.

Question 5

A survey pipeline estimates average household income with weighted.mean(income, survey_weight, na.rm = TRUE). Income is numeric, and nonrespondents have NA. The weights adjust for region and household size but not for prior income.

Which assumption is needed to interpret the result as an estimate of population average income rather than merely the average among respondents?

  1. Within the groups addressed by the weighting adjustment, income nonresponse is not systematically related to unobserved income, and NA does not mean zero income. (correct answer)
  2. Because income is numeric and na.rm = TRUE is specified, removing nonresponses cannot systematically alter the weighted population estimate.
  3. Every NA represents zero income, but excluding those zeros is acceptable because survey weights account for all omitted income values.
  4. Income nonresponse may depend arbitrarily on unobserved income, provided that every respondent has a positive numeric survey weight.
Explanation: Whenever you see a question about weighted estimation with missing data, your first instinct should be to think about missing data mechanisms — specifically, whether the missingness is random within the groups the weights already account for. The function weighted.mean(income, survey_weight, na.rm = TRUE) removes NA values and reweights the remaining observations. For this to recover the true population mean, you need the nonrespondents' income distribution to be similar to respondents' within each weighting cell (region × household size). This is the Missing At Random (MAR) assumption, conditional on the variables used in weighting. You also need NA to genuinely mean "not observed," not "zero" — otherwise exclusion introduces a different bias. That's exactly what A states, making it the correct answer. B is wrong because it treats na.rm = TRUE as a mathematical guarantee of unbiasedness. Removing NAs is simply a computational step — it says nothing about whether the missing values were random. Systematic nonresponse can absolutely distort a weighted estimate. C is wrong on two counts: it falsely assumes NA means zero income, and it incorrectly claims survey weights can compensate for omitted income values the weights weren't designed to address. D is wrong because having positive weights for all respondents doesn't rescue the estimate if nonresponse is driven by unobserved income. A high-earner who refuses to answer is simply absent from the data — no weight fixes that. A useful rule of thumb: weights adjust for who is sampled, not for why some people don't answer. Always ask what the weights actually control for before interpreting the estimate as population-level.

Question 6

A consent field is imported as character and contains Y, N, blank strings, and NA. An analyst wants a logical column for filtering records. Direct use of as.logical() does not interpret Y and N as intended.

Which assumption should guide the conversion?

  1. Y and N are both logically true because they are nonempty strings, blanks are logically false because they are empty, and imported NA is also logically false because it is absent.
  2. Y means TRUE, N means missing consent rather than refusal, blanks mean FALSE because no character was entered, and imported NA means consent was granted by default.
  3. Y means TRUE, N means FALSE, blanks mean refusal because nothing was selected, and imported NA means the field was not applicable to that respondent.
  4. Y means TRUE, N means FALSE, blanks and imported NA both mean unknown consent status, and no other codes are treated as valid without further review. (correct answer)
Explanation: When working with character fields that encode consent or survey responses, your job isn't to invent meaning — it's to preserve what's actually known and flag what isn't. This question tests whether you understand the difference between absence of a value and a known negative response. Y and N are explicit signals: the respondent actively indicated yes or no. Converting Y to TRUE and N to FALSE is the only defensible mapping because both represent deliberate answers. Blank strings and imported NA values, however, are ambiguous — a blank might mean the question was skipped, the data was lost, or the field simply wasn't applicable. Treating either as a definitive answer (TRUE or FALSE) imposes meaning that isn't there. The safe, analytically sound approach is to treat both as NA in the output logical column, flagging them for review. That's exactly what D describes. Choice A commits the classic coercion trap: nonempty strings in R do coerce to TRUE, but that makes N logically true, which is semantically wrong for consent data. Choice B invents a meaning for N (treating it as missing rather than refusal) and fabricates a default for NA (consent granted) — both are unsupported assumptions that could create serious errors in analysis. Choice C assigns "refusal" to blanks, which is a specific interpretation not warranted by the data; a blank is simply unknown, not equivalent to N. As a study strategy, whenever you see data-type conversion questions involving survey or consent fields, ask yourself: does this mapping add assumptions beyond what the data actually says? If yes, it's probably wrong.

Question 7

A risk column contains low, medium, high, and blank values. An analyst plans to encode risk numerically for an ordinal model. Calling factor(risk) without specifying levels would arrange the observed labels alphabetically.

Which assumption should be stated and implemented before producing the numeric encoding?

  1. Alphabetical factor order represents increasing risk, blanks represent the lowest risk, and any future label may receive the next available code.
  2. The only valid labels are the three documented categories, blanks mean unknown risk, and the intended order is set explicitly as low, medium, high. (correct answer)
  3. The three labels are nominal categories without an intended order, blanks mean no risk, and alphabetical integer codes are suitable model inputs.
  4. The labels already have numeric magnitude because they are character strings, blanks mean medium risk, and factor levels need not be specified.
Explanation: When encoding categorical text as ordered numbers for a model, you must make three explicit decisions before writing any code: what the valid categories are, what missing values mean, and what order the categories follow. This question tests whether you can identify the complete and correct set of those decisions for an ordinal encoding task. The only fully sound approach is B. It recognizes that the domain defines exactly three valid labels, treats blanks as genuinely unknown (not as a category with implied rank), and — most importantly — sets the factor levels explicitly with factor(risk, levels = c("low", "medium", "high"), ordered = TRUE). That single line encodes the business logic into the data structure, so the numeric codes 1, 2, 3 carry the intended meaning rather than an accidental alphabetical one. Choice A fails because alphabetical order gives high=1, low=2, medium=3, which reverses the real severity ranking and misrepresents blanks as having the lowest risk — a substantive error in an ordinal model. Choice C incorrectly declares the categories nominal, which would make integer codes meaningless for an ordinal model, and again misinterprets blanks as "no risk" rather than unknown. Choice D is doubly wrong: character strings carry no numeric magnitude in R (they are just text), and claiming blanks mean medium risk introduces an arbitrary imputation with no justification. A reliable study tip: whenever you see ordinal data in R, immediately ask yourself three questions — what levels exist, what do missing values mean, and what is the intended order? If any one of those is assumed rather than stated and coded explicitly, the analysis can silently produce incorrect results.

Question 8

A laboratory column contains concentrations such as 0.18, 0.04, and <0.01. The reporting unit is milligrams per liter, and <0.01 means the analyte was detected below the laboratory's quantification limit. A simple numeric coercion turns <0.01 into NA.

Which assumption most accurately describes the data before statistical analysis?

  1. All entries are exact numeric concentrations, <0.01 is malformed text, and coercion-generated NA represents an unobserved specimen.
  2. The <0.01 entries are exact zeros in milligrams per liter, while explicit NA values represent concentrations below the limit.
  3. Numeric entries are quantified in milligrams per liter, <0.01 is a left-censored observation rather than ordinary missingness, and explicit NA means unavailable. (correct answer)
  4. Numeric entries are quantified in grams per liter, <0.01 is ordinary missingness, and explicit NA should be replaced by the detection limit.
Explanation: When working with environmental or laboratory data in R, you need to distinguish between three fundamentally different data situations: a quantified measurement, a censored observation, and true missingness. Getting this wrong leads to biased statistical conclusions before you write a single line of analysis code. The value <0.01 is not a typo, a formatting error, or an absent measurement — it is a left-censored observation. The analyte was detected, but below the instrument's quantification limit. You know a real concentration exists somewhere in the interval (0, 0.01)(0,\ 0.01); you just cannot pin down the exact value. When R's as.numeric() coerces <0.01 to NA, it silently erases that information, which is why recognizing it as censored — not missing — is critical before any analysis. Explicit NA values, by contrast, mean the measurement simply was not recorded or is unavailable. Answer C captures all three layers correctly: quantified numerics in mg/L, left-censored <0.01, and explicit NA as truly unavailable. A is wrong because it mislabels censored data as "malformed text" and treats the coercion-generated NA as an unobserved specimen — both errors obscure the real data structure. B inverts the logic entirely: it calls <0.01 an exact zero (it isn't — zero would mean no detection at all) and misidentifies explicit NA as the below-limit value. D introduces a unit error (grams per liter vs. mg/L) and wrongly classifies censoring as ordinary missingness, then compounds the mistake by suggesting imputation with the detection limit without any censored-data methods. As a study strategy, whenever you see threshold notation like <value in a dataset, immediately think censoring, not missing data — these require specialized methods like Kaplan-Meier estimation or maximum likelihood, not simple na.omit().

Question 9

A pipeline processes a numeric sensor column with x[!is.finite(x)] <- NA_real_. The column can contain NaN after an undefined calculation and Inf after division by zero, although valid physical measurements are always finite.

Which assumption best justifies this transformation?

  1. Positive infinity is the largest measurable sensor value, negative infinity is the smallest, and only NaN should be interpreted as missing.
  2. is.na() and is.finite() identify exactly the same values, so the transformation only standardizes the storage type of existing NA values.
  3. NaN and infinite results do not represent valid physical measurements, both may be treated as missing for this analysis, and finite values retain their units. (correct answer)
  4. Every nonfinite value represents a measured zero in the sensor's units, and replacing it with NA_real_ preserves that numeric magnitude.
Explanation: When you see a question about data-cleaning transformations in R, ask yourself: what are the mathematical properties of the values being replaced, and why does the domain justify treating them as missing? is.finite(x) returns FALSE for NA, NaN, Inf, and -Inf — so writing x[!is.finite(x)] <- NA_real_ replaces all four of those non-finite cases with a proper missing value. In a physical sensor context, measurements must have bounded, real magnitudes. Neither Inf (produced by division by zero) nor NaN (produced by undefined operations like 0/0) corresponds to any real-world reading. Treating them as missing is scientifically sound, and replacing them with NA_real_ ensures downstream functions like mean() or lm() handle them consistently. That's exactly what C describes — and it correctly notes that finite values are untouched, preserving their units and numeric meaning. A is wrong because Inf and -Inf are not physically meaningful sensor extremes; they are arithmetic artifacts, not the largest or smallest legitimate readings. Keeping them would corrupt any statistical summary. B is wrong because is.na() and is.finite() are not equivalent. is.na() catches NA and NaN, but is.finite() additionally excludes Inf and -Inf. The transformation does real work beyond mere type standardization. D is wrong because non-finite values carry no numeric magnitude to preserve — replacing Inf with NA_real_ discards the infinity, it doesn't encode a measured zero. As a study tip, memorize R's four "not-real" values — NA, NaN, Inf, -Inf — and which detection functions catch which. Exam questions often hinge on those distinctions.

Question 10

An analyst combines package masses from two systems. System A records kilograms, and System B records pounds. The source system is retained in source, but the unit labels themselves were not exported. Some mass values are NA.

Which assumption should accompany a calculation of mean package mass in kilograms?

  1. All numeric masses can be treated as kilograms because the combined column has one R type; missing masses may simply be ignored.
  2. System labels reliably identify units, System B values are converted from pounds to kilograms before averaging, and NA means unknown mass. (correct answer)
  3. System labels reliably identify units, the mixed values are averaged first, and the resulting mean is then converted to kilograms.
  4. System A values are converted from kilograms to pounds, System B values remain unchanged, and the final mean is labeled kilograms.
Explanation: When combining data from multiple measurement systems, you must ask three questions before any calculation: Are the units consistent? How were missing values handled? What does "missing" actually mean? This question tests all three at once. The only statistically valid approach is B. It correctly identifies that the source column is trustworthy for distinguishing units, converts System B's pound values to kilograms using \text{kg} = \text{lbs} \div 2.205} before averaging, and treats NA as genuinely unknown — meaning you should use na.rm = TRUE carefully and acknowledge that those packages are excluded, not assumed to be zero. A is dangerously wrong because R stores both kilograms and pounds as the same numeric type. A single double column tells you nothing about real-world units — you'd be averaging apples and oranges (or kilograms and pounds), producing a meaningless result. Ignoring NA without acknowledgment compounds the error. C gets the conversion order backwards. Averaging mixed-unit values first and converting afterward is mathematically invalid. The mean of 10 kg and 22 lbs is not a real quantity — you cannot convert a mean of incompatible units into anything meaningful. D inverts the entire logic. Converting kilograms to pounds while leaving pounds unchanged would give you an all-pounds result, then mislabeling it as kilograms — a dangerous unit error that could go undetected downstream. Study tip: Whenever you see merged datasets in R, always verify unit consistency before any aggregation. Unit errors are invisible to R — the language won't warn you, so the analyst must.