R Indexing and Subsetting

Vector Indexing

Vectors can be indexed using numeric positions, negative indices (to exclude), or logical vectors.

Loading...
Output:

List Indexing

Use [[]] or $ for direct access to list elements.

Loading...
Output:

Matrix Indexing

Use [row, column] format to extract values or slices from matrices.

Loading...
Output:

Data Frame Subsetting

Data frames can be subset by position or logical condition.

Loading...
Output:

Logical Indexing

Use logical comparisons to filter values dynamically.

nums <- c(5, 10, 15, 20)

nums[nums > 10]    # 15, 20
nums[nums %% 2 == 0]  # even numbers

Dropping Dimensions

Prevent R from simplifying output (e.g., to vector) by setting drop=FALSE.

m[1, , drop=FALSE]    # Keeps first row as a matrix
df[ , "age", drop=FALSE]  # Keeps column as data frame

Best Practices

  • Always verify the result of subsetting using str() or class()
  • Use which() to get positions of TRUE values
  • Be explicit with row/column subsetting to avoid ambiguity

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic