Build a frequency table of counts and percentages for an R vector
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `freq_table(x)` in R. It summarizes an atomic vector (character, factor, logical or numeric) as a frequency distribution of counts and percentages. `NA` values are excluded before tabulating.
- Return a `data.frame` with columns `category` (character), `count` (integer) and `percent` (numeric).
- `percent` is `100 * count / total_non_NA`, rounded to 2 decimals.
- Sort by `count` descending, breaking ties by `category` ascending. Reset the row names to `1..n`.
- If there are no non-NA values, return a 0-row `data.frame` with the same three columns.
- Factor levels with zero occurrences after NA removal need not appear.
Example:
```r
x <- c("a", "b", "a", "c", "a", "b", NA)
freq_table(x)
# category count percent
# 1 a 3 50.00
# 2 b 2 33.33
# 3 c 1 16.67
```
```hint One label type for every input
Convert every supported input type to the same kind of label before counting, then look at what `table()` returns and how `order()` accepts more than one sort key.
```
### Constraints & Assumptions
- `x` is an atomic vector of type character, factor, logical or numeric, and may contain `NA`.
- Because `category` is character, the tie-break compares categories as strings.
### What a Strong Answer Covers
- Removing `NA` values before counting and computing percentages against the non-NA total.
- Treating all four input types the same way, including factors with unused levels.
- A two-key sort (count descending, category ascending) followed by a row name reset.
- The exact column types in both the normal and the 0-row result.
### Follow-up Questions
- How would you add a cumulative percentage column?
- How would you handle very large vectors efficiently?
- Why can the tie order differ between two machines, and how would you make it the same everywhere?
- The rounded percentages do not always add up to exactly 100. How would you handle a report that requires them to?
Overview: Write an R function that turns a character, factor, logical or numeric vector into a frequency table of counts and rounded percentages, excluding missing values. It tests table(), multi-key sorting with order(), exact column types and the empty-input case.