Create, inspect and coerce base R data types: integer, double, complex and character
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement four R functions that create, inspect and coerce the base R storage types integer, double, complex and character.
- `make_typed_values()` returns a named list, in this order: `integer = 10L`, `numeric = 2.5`, `complex = 1+2i`, `character = "R"`.
- `type_of(x)` returns a length-1 character value, `typeof(x)`.
- `classify_list(lst)` returns a character vector with the same length and names as `lst`, holding each element's `typeof()`.
- `coerce_to(x, to)` coerces `x` with the matching `as.*` function for `to` in `"integer"`, `"numeric"` (double, via `as.numeric`), `"complex"` and `"character"`. Any other `to` must call `stop()`.
Example:
```r
type_of(10L) # "integer"
type_of(2.5) # "double"
classify_list(list(a = 1L, b = "x")) # c(a = "integer", b = "character")
coerce_to(c("1", "2"), "integer") # c(1L, 2L)
```
```hint Literals and return types
Check what `typeof(10)` returns before you build the list, and think about which apply function still returns a character vector when `lst` is empty.
```
### What a Strong Answer Covers
- Each literal in `make_typed_values()` has the intended storage type, including the integer.
- `classify_list()` returns a character vector that keeps the names and length of its input, including for an empty list.
- `coerce_to()` maps `"numeric"` to double and rejects every other target, including values that are not a single string.
- What happens when a coercion cannot represent a value: `NA` with a warning, truncation, or a dropped imaginary part.
### Follow-up Questions
- How does `typeof()` differ from `class()` and `mode()`?
- What happens when coercion produces `NA`, and how would you make `coerce_to()` strict?
- Why does `as.numeric(factor(c("10", "20")))` return 1 and 2, and how do you get the original numbers back?
Overview: Implement four small R functions that build integer, double, complex and character values, report their storage type, and coerce between them. It tests typeof(), integer literals, vapply return types, switch defaults and how the as.* functions behave when a value cannot be converted.