One common error you may encounter in R is:
Error in x[, 4] : subscript out of bounds
This error occurs when you attempt to access a column or row in a matrix that does not exist.
This tutorial shares the exact steps you can use to troubleshoot this error, using the following matrix as an example:
#make this example reproducible set.seed(0) #create matrix with 10 rows and 3 columns x = matrix(data = sample.int(100, 30), nrow = 10, ncol = 3) #print matrix print(x) [,1] [,2] [,3] [1,] 14 51 96 [2,] 68 85 44 [3,] 39 21 33 [4,] 1 54 35 [5,] 34 74 70 [6,] 87 7 86 [7,] 43 73 42 [8,] 100 79 38 [9,] 82 37 20 [10,] 59 92 28
Example #1: Subscript out of bounds (with rows)
The following code attempts to access the 11th row of the matrix, which does not exist:
#attempt to display 11th row of matrix
x[11, ]
Error in x[11, ] : subscript out of bounds
Since the 11th row of the matrix does not exist, we get the subscript out of bounds error.
If we’re unaware of how many rows are in the matrix, we can use the nrow() function to find out:
#display number of rows in matrix
nrow(x)
[1] 10
We can see that there are only 10 rows in the matrix. Thus, we can only use numbers less than or equal to 10 when accessing the rows.
For example, we can use the following syntax to display the 10th row of the matrix:
#display 10th row of matrix
x[10, ]
[1] 59 92 28
Example #2: Subscript out of bounds (with columns)
The following code attempts to access the 4th column of the matrix, which does not exist:
#attempt to display 4th column of matrix
x[, 4]
Error in x[, 4] : subscript out of bounds
Since the 4th column of the matrix does not exist, we get the subscript out of bounds error.
If we’re unaware of how many columns are in the matrix, we can use the ncol() function to find out:
#display number of columns in matrix
ncol(x)
[1] 3
We can see that there are only 3 columns in the matrix. Thus, we can only use numbers less than or equal to 3 when accessing the columns.
For example, we can use the following syntax to display the 3rd column of the matrix:
#display 3rd column of matrix
x[, 3]
[1] 96 44 33 35 70 86 42 38 20 28
Example #3: Subscript out of bounds (rows & columns)
The following code attempts to access the value in the 11th row and the 4th column of the matrix, which does not exist:
#attempt to display value in 11th row and 4th column
x[11, 4]
Error in x[11, 4] : subscript out of bounds
Since neither the 11th row nor the 4th column of the matrix exist, we get the subscript out of bounds error.
If we’re unaware of how many rows and columns are in the matrix, we can use the dim() function to find out:
#display number of rows and columns in matrix
dim(x)
[1] 10 3
We can see that there are only 10 rows and 3 columns in the matrix. Thus, we can only use numbers less than or equal to these values when accessing the rows and columns.
For example, we can use the following syntax to display the value in the 10th row and the 3rd column of the matrix:
#display value in 10th row and 3rd column of matrix
x[10, 3]
[1] 28
Additional Resources
The following tutorials explain how to troubleshoot other common errors in R:
How to Fix in R: names do not match previous names
How to Fix in R: longer object length is not a multiple of shorter object length
How to Fix in R: contrasts can be applied only to factors with 2 or more levels
17 авг. 2022 г.
читать 2 мин
Одна распространенная ошибка, с которой вы можете столкнуться в R:
Error in x[, 4] : subscript out of bounds
Эта ошибка возникает при попытке доступа к столбцу или строке несуществующей матрицы.
В этом руководстве представлены точные шаги, которые вы можете использовать для устранения этой ошибки, используя следующую матрицу в качестве примера:
#make this example reproducible
set. seed (0)
#create matrix with 10 rows and 3 columns
x = matrix(data = sample. int (100, 30), nrow = 10, ncol = 3)
#print matrix
print(x)
[,1] [,2] [,3]
[1,] 14 51 96
[2,] 68 85 44
[3,] 39 21 33
[4,] 1 54 35
[5,] 34 74 70
[6,] 87 7 86
[7,] 43 73 42
[8,] 100 79 38
[9,] 82 37 20
[10,] 59 92 28
Пример №1: нижний индекс выходит за пределы (со строками)
Следующий код пытается получить доступ к 11-й строке матрицы, которой не существует:
#attempt to display 11th row of matrix
x[11, ]
Error in x[11, ] : subscript out of bounds
Поскольку 11-й строки матрицы не существует, мы получаем индекс ошибки выхода за границы .
Если мы не знаем, сколько строк в матрице, мы можем использовать функцию nrow() , чтобы узнать:
#display number of rows in matrix
nrow(x)
[1] 10
Мы видим, что в матрице всего 10 строк. Таким образом, мы можем использовать только числа меньше или равные 10 при доступе к строкам.
Например, мы можем использовать следующий синтаксис для отображения 10-й строки матрицы:
#display 10th row of matrix
x[10, ]
[1] 59 92 28
Пример №2: нижний индекс выходит за пределы (со столбцами)
Следующий код пытается получить доступ к 4-му столбцу несуществующей матрицы:
#attempt to display 4th column of matrix
x[, 4]
Error in x[, 4] : subscript out of bounds
Поскольку 4-й столбец матрицы не существует, мы получаем индекс ошибки выхода за границы .
Если мы не знаем, сколько столбцов в матрице, мы можем использовать функцию ncol() , чтобы узнать:
#display number of columns in matrix
ncol(x)
[1] 3
Мы видим, что в матрице всего 3 столбца. Таким образом, мы можем использовать только числа меньше или равные 3 при доступе к столбцам.
Например, мы можем использовать следующий синтаксис для отображения третьего столбца матрицы:
#display 3rd column of matrix
x[, 3]
[1] 96 44 33 35 70 86 42 38 20 28
Пример № 3: нижний индекс выходит за пределы (строки и столбцы)
Следующий код пытается получить доступ к несуществующему значению в 11-й строке и 4-м столбце матрицы:
#attempt to display value in 11th row and 4th column
x[11, 4]
Error in x[11, 4] : subscript out of bounds
Поскольку ни 11-й строки, ни 4-го столбца матрицы не существует, мы получаем нижний индекс ошибки выхода за границы .
Если мы не знаем, сколько строк и столбцов в матрице, мы можем использовать функцию dim() , чтобы узнать:
#display number of rows and columns in matrix
dim(x)
[1] 10 3
Мы видим, что в матрице всего 10 строк и 3 столбца. Таким образом, мы можем использовать только числа, меньшие или равные этим значениям, при доступе к строкам и столбцам.
Например, мы можем использовать следующий синтаксис для отображения значения в 10-й строке и 3-м столбце матрицы:
#display value in 10th row and 3rd column of matrix
x[10, 3]
[1] 28
Дополнительные ресурсы
В следующих руководствах объясняется, как устранять другие распространенные ошибки в R:
Как исправить в R: имена не совпадают с предыдущими именами
Как исправить в R: более длинная длина объекта не кратна более короткой длине объекта
Как исправить в R: контрасты могут применяться только к факторам с 2 или более уровнями
This R error is very common: it occurs when you try to use an index value for a matrix, array or list data object where no element exists for that value because it is outside the upper bound of that range. For example, you are asking for the 11th element of a 10 element array. Since it doesn’t exist… here’s your bounds error…. This is also known as an array index overflow error in other languages.
If you get the subscript out of bounds error code, the best place to look for the bug is how you are calculating the array index value you are requesting. Look at r code where you are using a for loop to traverse defined ranges of array index values: one of these is probably off by one unit and iterating past the end of the defined range for the matrix, list, or array. If the array has multiple dimension(s), you may be requesting a dimension value which hasn’t been defined yet for that object. Similar issues can occur if you’re working with collections of custom data objects with mixed states and sparse data.
The circumstances of this error.
This error message occurs when you input an index into a matrix that is too large for that matrix. In a simple program, it is unlikely to occur but in more complex programs there are several ways that can occur by accident.
> x = matrix(0,5,7)
> for(i in 1:6)
+ {x[i,i] = 1}
Error in `[=`(`*tmp*`, i, i, value = 1) : subscript out of bounds
Here, we have an example of a for-loop for incrementally accessing locations in the matrix “X”, and it goes further than the bounds of the matrix. This is the most common type of situation in which this error is likely to occur. It can happen just because you forget the size of the matrix.
What is causing this error?
The cause of this error is quite simple and easy to fix. It results from trying to access an index number that is out of the range of a matrix.
> x = matrix(0,5,7)
> x[6,6]
Error in x[6, 6] : subscript out of bounds
This is an extremely simple example and one you should never make in actual practice. In this case, it is a deliberate setup to illustrate the error message. Looking at this bit of code, you will see that “x” is a 5 X 7 matrix. However, the second line calls position 6,6 which is too big for the first index, and so the subscript is out of bounds.
Fixing this error message is simply a matter of making sure that you never try to access an index for a matrix that is out of range
> x = matrix(0,5,7)
> for(i in 1:5)
+ {x[i,i] = 1}
Note how in this example the for-loop end at 5 rather than 6 and as a result does not go out of bounds. One way to prevent this from happening is to use the nrow() and ncol() functions for any for-loop indexing the rows or columns respectively.
> x = matrix(0,5,7)
> for(i in 1:nrow(x))
+ { for(j in 1:ncol(x))
+ {x[i,j] = 1}}
This simple piece of code is an example of this type of fix for the for-loop situation. Ultimately, the key to fixing this problem is making sure that any value you use to index a matrix, remains inside the bounds of the matrix. The nrow() and ncol() functions are also a good way to check the validity of a value before accessing any part of a matrix.
Subscript out of bounds: It is one of the most common errors that one may encounter in R and has the following form:
Error in y[,6]: subscript out of bounds
Reason: The compiler produces this error when a programmer tries to access a row or column that doesn’t exist.
Creating a matrix:
Let us firstly create a matrix. For example, we have created a matrix mat having 5 rows and 3 columns. Its values are initialized using sample.int() function. This function is used for taking random elements from a dataset.
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
print(mat)
Output:

Output
Example 1: Subscript out of bounds (in rows):
The below code is trying to access the 6th row that doesn’t exist.
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
mat[6, ]
Output:

Output
The 6th row of the matrix does not exist therefore we are getting the subscript out of bounds error. Note that we can always use nrow() function to check how many rows are there in the matrix:
Example:
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
nrow(mat)
Output:

Output
There are only 5 rows in the matrix. Hence, we can access the column less than or equal to 5. Now let’s try to access the 3rd column.
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
mat[5,]
Output:

Output
Example 2: Subscript out of bounds (in columns).
The below code is trying to access the 4th column that doesn’t exist.
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
mat[, 4]
Output:

Output
The 4th column of the matrix does not exist therefore we are getting the subscript out of bounds error. Note that we can always use ncol() function to check how many columns are there in the matrix.
Example:
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
ncol(mat)
Output:

Output
There are only 3 columns in the matrix. Hence, we can access the column less than or equal to 3. Now let’s try to access the 3rd column.
Example:
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
mat[, 3]
Output:

Output
Example 3: Subscript out of bounds (both rows & columns):
The below code is trying to access the 6th row and the 4th column.
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
mat[6, 4]
Output:

Output
The 6th row and the 4th column of the matrix do not exist therefore we are getting the subscript out of bounds error. Note that we can always use dim() function to check how many rows and columns are there in the matrix.
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
dim(mat)
Output:

Output
There are only 5 rows and 3 columns in the matrix. Hence, we can access the row less than or equal to 5 and the column less than or equal to 3. Now let’s try to access the value stored at the 5th row and the 3rd column.
R
mat = matrix(data = sample.int(100, 30), nrow = 5, ncol = 3)
mat[5,3]
Output:

Output
If you try to access a column or row that does not exist, you will raise the error Subscript out of bounds.
You can use nrows(matrix) to find the number of rows of a matrix, ncol(matrix) to find the number of columns in a matrix and dim(matrix) to find the number of rows and columns in a matrix.
Once you know the number of rows and columns, you can index the matrix within those bounds.
This tutorial will go through the error in detail and how to solve it with code examples.
Table of contents
- Example #1: Subscript out of bounds with number of rows
- Example #2: Subscript out of bounds with number of columns
- Example #3: Subscript out of bounds with number of rows and columns
- Summary
Example #1: Subscript out of bounds with number of rows
Let’s create a matrix with 8 rows and 5 columns.
set.seed(0) mat = matrix(data=sample.int(100, 40), nrow= 8, ncol=5) print(mat)
[,1] [,2] [,3] [,4] [,5] [1,] 32 70 23 21 34 [2,] 14 87 29 31 10 [3,] 2 92 91 17 1 [4,] 45 75 95 73 43 [5,] 18 81 28 79 59 [6,] 22 13 85 64 26 [7,] 78 40 33 60 15 [8,] 65 48 97 51 58
Let’s try to access the 9th row of the matrix:
print(mat[9,])
Error in mat[9, ] : subscript out of bounds
The error occurs because there are only 8 rows in the matrix. We can use nrow() to find out how many rows are in the matrix:
print(nrow(mat))
[1] 8
The nrow() function confirms there are only eight rows. Let’s see what happens when we try to retrieve the 8th row of the matrix:
print(mat[8,])
65 48 97 51 58
We successfully retrieved the 8th row of the matrix.
Example #2: Subscript out of bounds with number of columns
Let’s try to access the 6th column of the matrix:
print(mat[,6])
Error in mat[, 6] : subscript out of bounds
The error occurs because there are only 5 columns in the matrix. We can use ncol() to find out how many columns are in the matrix:
print(ncol(mat))
[1] 5
The ncol() function confirms there are only 5 columns. Let’s see what happens when we try to retrieve the 5th row of the matrix:
print(mat[,5])
[1] 34 10 1 43 59 26 15 58
We successfully retrieved the 5th column of the matrix.
Example #3: Subscript out of bounds with number of rows and columns
Let’s try to access the value at the 9th row of the 6th column of the matrix:
print(mat[9,6])
Error in mat[9, 6] : subscript out of bounds
The error occurs because there are only 9 rows and 5 columns in the matrix. We can use dim() to find out how many rows and columns are in the matrix:
print(dim(mat))
[1] 8 5
The dim() function confirms there are only 8 rows and 5 columns in the matrix. Let’s see what happens when we try to retrieve the value at the matrix’s 5th row and 8th column.
print(mat[8,5])
[1] 58
Summary
Congratulations on reading to the end of this tutorial! The error Subscript out of bounds occurs when you try to access the column or row of a matrix that does not exist in the matrix. You can solve this error by checking the dimensions of the matrix and indexing within those bounds.
For further reading on R related errors, go to the articles:
- How to Solve R Error: $ operator is invalid for atomic vectors
- How to Solve R Error: object of type ‘closure’ is not subsettable
- How to Solve R Error: object not found
Go to the online courses page on R to learn more about coding in R for data science and machine learning.
Have fun and happy researching!
Error message that came up while using SMOTE function from DMwR package in R is captured below, along with its reason and fix.
Error message:
Error in T[i, ] : subscript out of bounds
In addition: Warning messages:
1: In FUN(newX[, i], …) :
no non-missing arguments to max; returning -Inf
2: In FUN(newX[, i], …) :
no non-missing arguments to max; returning -Inf
3: In FUN(newX[, i], …) :
no non-missing arguments to max; returning -Inf
4: In FUN(newX[, i], …) :
no non-missing arguments to max; returning -Inf
5: In FUN(newX[, i], …) : no non-missing arguments to min; returning Inf
6: In FUN(newX[, i], …) : no non-missing arguments to min; returning Inf
7: In FUN(newX[, i], …) : no non-missing arguments to min; returning Inf
8: In FUN(newX[, i], …) : no non-missing arguments to min; returning Inf
Reason:
This error occurs when the target variable you use for SMOTE function is of INT data type. SMOTE can only work with factor target variable.
R line of code that gives error is
> Traindata_SMOTE = SMOTE(Target ~ .,Traindata[,-1], perc.over = 300, perc.under = 500)
STR command reveals that the target variable is INT.
> str(Traindata)
'data.frame': 4994 obs. of 6 variables: $ Casenum : int 1 2 3 4 5 6 7 8 9 10 ... $ Target : int 1 0 0 0 0 0 0 0 0 0 ... $ ..
Fix:
Simply convert the target variable to “factor” as below
> Traindata$Target = as.factor(Traindata$Target)
Rerun SMOTE and it will go through fine.
