VOOZH about

URL: https://www.geeksforgeeks.org/r-language/how-to-use-the-drop-function-in-r/

⇱ How to Use the drop() Function in R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Use the drop() Function in R

Last Updated : 23 Jul, 2025

In R Language the drop() function is used to eliminate redundant dimensions of an object, such as dropping dimensions from a matrix, data frame, or array. The function simplifies the structure by reducing the number of dimensions when the result has only one row one column, or both. This can be particularly useful when working with subsets of matrices or arrays, where R may automatically retain a higher dimension structure even when it's not necessary.

The basic syntax of the drop() function is:

drop(x)

  • x: The object (matrix, array, or data frame) from which dimensions should be dropped.

When to Use drop()

The drop() function is commonly used when you want to reduce the dimensions of an array or matrix that results from subsetting. Without explicitly using drop(), R may retain the original dimensions, even when they are no longer needed.

Example 1: Using drop() with a Matrix

Consider a matrix m with 3 rows and 3 columns.

Output:

 [,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

[,1]
[1,] 1

Here, the result retains the matrix structure with one row and one column. To remove this unnecessary dimension, use the drop() function:

Example 2: Using drop() with an Array

Consider a 3-dimensional array.

Output:

, , 1

[,1] [,2]
[1,] 1 3
[2,] 2 4

, , 2

[,1] [,2]
[1,] 5 7
[2,] 6 8

, , 3

[,1] [,2]
[1,] 9 11
[2,] 10 12


[,1] [,2] [,3]
[1,] 1 5 9
[2,] 3 7 11

Example 3: Using drop() with Data Frames

While drop() is most commonly used with matrices and arrays, it can also be used to simplify data frames when necessary.

Output:

 A B
1 1 4
2 2 5
3 3 6

[1] 1 2 3

A
1 1
2 2
3 3

A
1 1
2 2
3 3
  • Using drop = FALSE can force R to retain the data frame structure:

Conclusion

The drop() function is a useful tool in R for reducing unnecessary dimensions in matrices, arrays, and data frames. It simplifies the structure of an object by eliminating dimensions that are no longer needed after subsetting. This function becomes particularly handy when dealing with high-dimensional data and helps make the results easier to interpret.

Comment
Article Tags:
Article Tags:

Explore