How to use the drop function in R?

The drop() function in R is used to remove columns or rows from a data frame. It takes two arguments, the data frame and a vector of labels, either row numbers or column names, to specify which columns or rows to remove. The drop() function returns a new data frame with the specified columns or rows removed.


The drop() function in base R can be used to delete the dimensions of an array or matrix that only have one level.

The following examples show how to use this function in practice.

Example 1: Use drop() to Delete Dimensions with One Level in Array

Suppose we have the following 3-dimensional array in R:

#create 3-dimensional array
my_array <- c(1:10)
dim(my_array ) <- c(1,2,5)

#view array
my_array

, , 1

     [,1] [,2]
[1,]    1    2

, , 2

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

, , 3

     [,1] [,2]
[1,]    5    6

, , 4

     [,1] [,2]
[1,]    7    8

, , 5

     [,1] [,2]
[1,]    9   10

We can use the drop() function to drop the dimension that only has one level in the array:

#drop dimensions with only one level
new_array <- drop(my_array)

#view new array
new_array

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

Notice that the dimension with only one level has been dropped.

We can use the dim() function to view the new dimensions:

#view dimensions of new array
dim(new_array)

[1] 2 5

We can see that the new array only has two dimensions.

Example 2: Use drop() to Delete Dimensions with One Level in Matrix

Suppose we have the following matrix with seven columns and one row in R:

#create matrix
my_matrix <- matrix(1:7, ncol=7)

#view matrix
my_matrix

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

#view dimensions of matrix
dim(my_matrix)

[1] 1 7

We can use the drop() function to drop the dimension that only has one level in the matrix:

#drop dimensions with only one level
new_matrix <- drop(my_matrix)

#view new matrix
new_matrix

[1] 1 2 3 4 5 6 7

Notice that the dimension with only one level has been dropped.

If we use the dim() function to view the dimensions, it will return NULL since the new object is no longer a matrix with two dimensions:

#view dimensions of new matrix
dim(new_matrix)

NULL

Instead, we can use length() to display the length of the vector:

#view length
length(new_matrix)

[1] 7

We can see that our vector has 7 elements in it.

The following tutorials explain how to perform other common tasks in R:

x