Deduplicating Data Frames in R With duplicated()
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement side-effect-free base R helpers for removing duplicate rows and values.
- `remove_duplicates(df)`: return unique rows only, keeping the first occurrence and the original column order, with row names reset to `1..n`.
- `count_duplicates(df)`: return a single integer equal to `sum(duplicated(df))`.
- `remove_duplicates_by(df, cols)`: return the first row for each unique combination of the columns in `cols` (a character vector), keeping all columns, with row names reset to `1..n`.
- `unique_values(x)`: return the distinct values of the atomic vector `x` in first-appearance order (the same as `x[!duplicated(x)]`).
Example:
```r
df <- data.frame(id = c(1, 1, 2), name = c("a", "a", "b"))
remove_duplicates(df)
# id name
# 1 1 a
# 2 2 b
count_duplicates(df)
# [1] 1
unique_values(c(3, 3, 1, 3))
# [1] 3 1
df2 <- data.frame(id = c(1, 1, 2), name = c("a", "b", "c"))
remove_duplicates_by(df2, "id")
# id name
# 1 1 a
# 2 2 c
```
The second row of `df` repeats the first, so it is dropped and counted once. In `df2` no two full rows are equal, but rows 1 and 2 share `id` 1, so only the first of them is kept.
```hint Start from one logical vector
One base function flags every row or element that has an identical earlier one. Check what subsetting rows with its negation returns when the data frame has a single column.
```
### Constraints & Assumptions
- Base R only. The functions must not modify their inputs, print, or change global state.
- `cols` is a non-empty character vector of column names that exist in `df`.
### What a Strong Answer Covers
- Using `duplicated()` and its negation to keep first occurrences in the original order
- Keeping the result a data frame for one-column inputs and resetting row names
- Restricting the duplicate check to `cols` while returning every column
- Returning an integer count, and keeping every function free of side effects
- How `NA` values and floating-point values are compared
### Follow-up Questions
- How would you keep the last occurrence instead of the first?
- How does `duplicated()` handle `NA` values?
- How would you return every row involved in a duplicate group, including the first occurrence?
Overview: Write base R helpers that drop duplicate rows, count them, deduplicate on a subset of key columns, and return distinct values in first-appearance order. It tests how duplicated() works, keeping data frame shape, resetting row names and handling NA values.