# Error in x[6, ]: subscript out of bounds

Subscript out of bounds, Subscript out of limits in R: How to Fix?

The following is an example of a typical R error:

Error in x[6, ] : subscript out of bounds

When you try to access a column or row in a matrix that doesn’t exist, you’ll get this error.

## Subscript out of bounds

Using the following matrix as an example, this guide explains the exact procedures to troubleshoot this error.

Reading Data From Excel Files (xls,xlsx,csv) into R-Quick Guide »

set.seed(123)

Let’s create a matrix with 5 rows and 3 columns

x = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3) x

[,1] [,2] [,3] [1,] 36 84 5 [2,] 87 3 19 [3,] 100 66 98 [4,] 26 86 74 [5,] 55 76 94

## Approach 1: Subscript out of bounds (with rows)

The code below tries to access the matrix’s 6th row, which does not exist.

Extract text from pdf in R and word Detection »

x[6, ]

Error in x[6, ] : subscript out of bounds

We get the subscript out of limits error because the 6th row of the matrix does not exist.

We can use the nrow() function to figure out how many rows are in the matrix if we don’t know:

nrow(x) [1] 5

The matrix only has five rows, as we can see. As a result, we can only access the rows with integers less than or equal to 5.

## Approach 2: Subscript out of bounds (with columns)

The following code tries to access the matrix’s fourth column, which doesn’t exist:

Bubble Chart in R-ggplot & Plotly » (Code & Tutorial) »

x[, 4]

Error in x[, 4] : subscript out of bounds

The subscript out of limits error occurs because the fourth column of the matrix does not exist.

If we don’t know how many columns the matrix has, we can use the ncol() function to figure it out.

ncol(x) [1] 3

The matrix only has three columns, as we can see. As a result, we can only access the columns with integers less than or equal to three.

aggregate Function in R- A powerful tool for data frames »

## Approach 3: Subscript out of bounds (rows & columns)

The following code tries to access a value in the matrix’s 6th row and 4th column that does not exist.

x[6, 4]

Error in x[6, 4] : subscript out of bounds

We get the subscript out of limits error because neither the 6th row nor the 4th column of the matrix exists.

We can use the dim() function to figure out how many rows and columns are in the matrix if we don’t know:

dim(x) [1] 5 3

The matrix has only 5 rows and 3 columns, as can be seen. As a result, while accessing the rows and columns, we can only utilize numbers that are less than or equal to these values.

rbind in r-Combine Vectors, Matrix or Data Frames by Rows »