Build an S3 dataset Class in R With a Constructor, print and summary Methods
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Build an S3 class `"dataset"` in R that wraps a labelled numeric sample, with a constructor, a type predicate, and `summary` and `print` methods.
- `new_dataset(values, label)` returns a list of class `"dataset"` with elements `values` (numeric, length at least 1) and `label`. It calls `stop()` if `values` is not a non-empty numeric vector or `label` is not a length-1 character vector.
- `is_dataset(x)` returns a single logical, `TRUE` if and only if `x` inherits from `"dataset"`.
- `summary.dataset(object, ...)` returns a named numeric vector with names exactly `c("n", "mean", "sd", "median", "min", "max")`, where `n` is `length(values)` as a numeric and `sd` is the sample standard deviation.
- `print.dataset(x, ...)` prints exactly three lines with `cat()` and returns `x` invisibly. The lines are `paste0("Dataset: ", label)`, `paste0("Observations: ", n)` and `paste0("Mean: ", sprintf("%.3f", mean(values)))`.
Example:
```r
d <- new_dataset(c(1, 2, 3, 4), "heights")
is_dataset(d) # TRUE
summary(d) # named numeric: n mean sd median min max
print(d)
# Dataset: heights
# Observations: 4
# Mean: 2.500
```
```hint Check the summary types
`length()` returns an integer and `sd()` needs at least two values. Work out what each entry of the summary vector is for integer input and for a single observation.
```
### What a Strong Answer Covers
- Validating `values` and `label` in the constructor before building the object, and storing `values` as double
- Setting the class attribute so `print()` and `summary()` dispatch to the `.dataset` methods
- A named double vector from `summary` with the exact names and the sample standard deviation
- Exactly three `cat()` lines from `print`, an invisible return of `x`, and a correct reason for returning it that way
- Edge cases such as a single observation, `NA` values and an `NA` label
### Follow-up Questions
- How would you add a validator separate from the constructor?
- Why return `x` invisibly from `print`?
- What changes when this class lives in a package instead of a script?
Overview: Build an S3 class in R that wraps a labelled numeric sample, with a validating constructor, a class predicate, and summary and print methods that produce exact output. It tests S3 method dispatch, input validation, sample statistics, and why print methods return their object invisibly.