 # drop() Function In R: Removes Redundant Dimension This tutorial will discuss how to drop() function in the R programming language. So, read the code example below to get to understand it better.

## What is the drop() function in R?

The drop() function will remove redundant dimension information. And it deletes array, vector, or matrix dimensions with only one level.

We can see the syntax below.

Syntax:

drop(x)

Parameters:

• x: The array , vector , matrix …

## How to use the drop() function in R?

### Using the drop() function with an array or vector

Here, we will create data for this example as follows:

# Create a data
data <- c(1:16)

# Set dim for a vector
dim(data) <- c(1, 4, 4)

# View a data
cat('The data is:\n')
data

Output

The data is:
, , 1

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

, , 2

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

, , 3

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

, , 4

[,1] [,2] [,3] [,4]
[1,]   13   14   15   16

So, we will apply the drop() function to this data.

# Create a data
data <- c(1:16)

# Set dim for a vector
dim(data) <- c(1, 4, 4)

# Using drop() function
data1 <- drop(data)

# View
cat("The new data is:\n")
data1
cat("The new dim is:\n", dim(data1))

Output

The new data is:
[,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16
The new dim is:
4 4

### Using the drop() function with a matrix

We will create a matrix as follows:

# Create a matrix
x <- matrix(5:10, ncol = 6)

# View a matrix
cat("The matrix is:\n")
x
cat("The dim of the matrix is:\n")
dim(x)

Output

The matrix is:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,]    5    6    7    8    9   10

The dim of the matrix is:
 1 6

Now, we use the drop() function for this matrix. See the code example below:

# Create a matrix
x <- matrix(5:10, ncol = 6)

# Apply the drop() function
res <- drop(x)

# View a matrix
cat("The new matrix is:\n")
res
cat("The new dim of the matrix is:\n")
dim(res)

Output

The new matrix is:
  5  6  7  8  9 10
The new dim of the matrix is:
NULL

As you can see, we removed the unnecessary dimensions, and the dim() function returns NULL, indicating that no dimensions remain.

## Summary

This tutorial will demonstrate the drop() function in the R programming language. Please leave a comment if you have any queries. Good luck!

Maybe you are interested:

Posted in R