How do positive, negative, logical, and name-based indexing work in R?
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
How do positive, negative, logical, and name-based indexing work in R? Explain what each kind of index selects with the `[` operator, and how the same ideas carry over to data frames.
```hint Try the edge cases
For each kind of index, think about what R does with a value it can't match: a zero, a position past the end, an `NA`, or a name that does not exist.
```
### What a Strong Answer Covers
- What each of the four index types selects, with a short example
- The rules that trip people up, such as mixing positive and negative indices, zero, and out-of-range positions
- How `NA` values and recycling behave in a logical index
- How the same indexing applies to each dimension of a data frame or matrix
### Follow-up Questions
- Why can `x[-which(x > 100)]` return an empty vector, and how do you write it safely?
- How does `[` differ from `[[` and `$` on a list or data frame?
- What does `df[df$score > 80, ]` return when `score` has missing values?
- What happens when you index by a name that appears twice in the vector?
Overview: Asks how positive, negative, logical and name-based indexing select elements with the bracket operator in R, on vectors and on data frames. Tests everyday R fluency, including the edge cases around zero, out-of-range positions, missing values and recycled masks.