Subscript out of bounds ошибка

  • Редакция Кодкампа


читать 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 или более уровнями


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

In this R tutorial you’ll learn how to fix the error message subscript out of bounds.

The article is structured as follows:

Let’s start right away.

Creating Example Data

First, we’ll have to create some example data:

my_mat <- matrix(1:20, ncol = 5)    # Create example matrix
my_mat                              # Print example matrix
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    5    9   13   17
# [2,]    2    6   10   14   18
# [3,]    3    7   11   15   19
# [4,]    4    8   12   16   20

Have a look at the previous output of the RStudio console. It shows that our example data is a numeric matrix consisting of four rows and five columns.

Example: Reproducing & Solving the Error: Subscript Out of Bounds

This Example shows the reason why the error message “subscript out of bounds” occurs.

Let’s assume that we want to extract certain rows or columns of our matrix. Then we could apply the following R code:

my_mat[3, ]                         # Printing third row of matrix
# [1]  3  7 11 15 19

As you can see in the previous output, we extracted the third row of our data set.

Now, let’s assume that we want to extract a row that doesn’t exist in our data (i.e. the 10th row):

my_mat[10, ]                        # Trying to print tenth row of matrix
# Error in my_mat[10, ] : subscript out of bounds

Then the R programming language returns the error message “subscript out of bounds”.

In other words: If you are receiving the error message “subscript out of bounds” you should check whether you are trying to use a data element that does not exist in your data.

Video, Further Resources & Summary

Do you need more info on the R codes of this tutorial? Then you could have a look at the following video which I have published on my YouTube channel. In the video, I show the R code of this tutorial:

In addition, you might want to have a look at the other articles on my homepage.

  • The R Programming Language

On this page you learned how to solve the error subscript out of bounds in R programming. In case you have additional questions, let me know in the comments below. Furthermore, please subscribe to my email newsletter in order to receive updates on the newest articles.

When working with R I frequently get the error message «subscript out of bounds». For example:

# Load necessary libraries and data
library(igraph)
library(NetData)
data(kracknets, package = "NetData")

# Reduce dataset to nonzero edges
krack_full_nonzero_edges <- subset(krack_full_data_frame, (advice_tie > 0 | friendship_tie > 0 | reports_to_tie > 0))

# convert to graph data farme 
krack_full <- graph.data.frame(krack_full_nonzero_edges) 

# Set vertex attributes
for (i in V(krack_full)) {
    for (j in names(attributes)) {
        krack_full <- set.vertex.attribute(krack_full, j, index=i, attributes[i+1,j])
    }
}

# Calculate reachability for each vertix
reachability <- function(g, m) {
    reach_mat = matrix(nrow = vcount(g), 
                       ncol = vcount(g))
    for (i in 1:vcount(g)) {
        reach_mat[i,] = 0
        this_node_reach <- subcomponent(g, (i - 1), mode = m)

        for (j in 1:(length(this_node_reach))) {
            alter = this_node_reach[j] + 1
            reach_mat[i, alter] = 1
        }
    }
    return(reach_mat)
}

reach_full_in <- reachability(krack_full, 'in')
reach_full_in

This generates the following error Error in reach_mat[i, alter] = 1 : subscript out of bounds.

However, my question is not about this particular piece of code (even though it would be helpful to solve that too), but my question is more general:

  • What is the definition of a subscript-out-of-bounds error? What causes it?
  • Are there any generic ways of approaching this kind of error?

asked Feb 22, 2013 at 19:00

histelheim's user avatar

2

This is because you try to access an array out of its boundary.

I will show you how you can debug such errors.

  1. I set options(error=recover)
  2. I run reach_full_in <- reachability(krack_full, 'in')
    I get :

    reach_full_in <- reachability(krack_full, 'in')
    Error in reach_mat[i, alter] = 1 : subscript out of bounds
    Enter a frame number, or 0 to exit   
    1: reachability(krack_full, "in")
    
  3. I enter 1 and I get

     Called from: top level 
    
  4. I type ls() to see my current variables

      1] "*tmp*"           "alter"           "g"               
         "i"               "j"                     "m"              
        "reach_mat"       "this_node_reach"
    

Now, I will see the dimensions of my variables :

Browse[1]> i
[1] 1
Browse[1]> j
[1] 21
Browse[1]> alter
[1] 22
Browse[1]> dim(reach_mat)
[1] 21 21

You see that alter is out of bounds. 22 > 21 . in the line :

  reach_mat[i, alter] = 1

To avoid such error, personally I do this :

  • Try to use applyxx function. They are safer than for
  • I use seq_along and not 1:n (1:0)
  • Try to think in a vectorized solution if you can to avoid mat[i,j] index access.

EDIT vectorize the solution

For example, here I see that you don’t use the fact that set.vertex.attribute is vectorized.

You can replace:

# Set vertex attributes
for (i in V(krack_full)) {
    for (j in names(attributes)) {
        krack_full <- set.vertex.attribute(krack_full, j, index=i, attributes[i+1,j])
    }
}

by this:

##  set.vertex.attribute is vectorized!
##  no need to loop over vertex!
for (attr in names(attributes))
      krack_full <<- set.vertex.attribute(krack_full, 
                                             attr, value = attributes[,attr])

zx8754's user avatar

zx8754

52.8k12 gold badges114 silver badges212 bronze badges

answered Feb 22, 2013 at 19:16

agstudy's user avatar

agstudyagstudy

120k17 gold badges199 silver badges261 bronze badges

3

It just means that either alter > ncol( reach_mat ) or i > nrow( reach_mat ), in other words, your indices exceed the array boundary (i is greater than the number of rows, or alter is greater than the number of columns).

Just run the above tests to see what and when is happening.

answered Feb 22, 2013 at 19:07

January's user avatar

JanuaryJanuary

16.4k6 gold badges53 silver badges74 bronze badges

Only an addition to the above responses: A possibility in such cases is that you are calling an object, that for some reason is not available to your query. For example you may subset by row names or column names, and you will receive this error message when your requested row or column is not part of the data matrix or data frame anymore.
Solution: As a short version of the responses above: you need to find the last working row name or column name, and the next called object should be the one that could not be found.
If you run parallel codes like «foreach», then you need to convert your code to a for loop to be able to troubleshoot it.

answered Aug 22, 2017 at 20:31

Farshad's user avatar

If this helps anybody, I encountered this while using purr::map() with a function I wrote which was something like this:

find_nearby_shops <- function(base_account) {
   states_table %>% 
        filter(state == base_account$state) %>% 
        left_join(target_locations, by = c('border_states' = 'state')) %>% 
        mutate(x_latitude = base_account$latitude,
               x_longitude = base_account$longitude) %>% 
        mutate(dist_miles = geosphere::distHaversine(p1 = cbind(longitude, latitude), 
                                                     p2 = cbind(x_longitude, x_latitude))/1609.344)
}

nearby_shop_numbers <- base_locations %>% 
    split(f = base_locations$id) %>% 
    purrr::map_df(find_nearby_shops) 

I would get this error sometimes with samples, but most times I wouldn’t. The root of the problem is that some of the states in the base_locations table (PR) did not exist in the states_table, so essentially I had filtered out everything, and passed an empty table on to mutate. The moral of the story is that you may have a data issue and not (just) a code problem (so you may need to clean your data.)

Thanks for agstudy and zx8754’s answers above for helping with the debug.

answered Jan 23, 2019 at 19:03

John Paul Cassil's user avatar

I sometimes encounter the same issue. I can only answer your second bullet, because I am not as expert in R as I am with other languages. I have found that the standard for loop has some unexpected results. Say x = 0

for (i in 1:x) {
  print(i)
}

The output is

[1] 1
[1] 0

Whereas with python, for example

for i in range(x):
  print i

does nothing. The loop is not entered.

I expected that if x = 0 that in R, the loop would not be entered. However, 1:0 is a valid range of numbers. I have not yet found a good workaround besides having an if statement wrapping the for loop

answered Feb 22, 2013 at 19:19

James Pringle's user avatar

1

This came from standford’s sna free tutorial
and it states that …

# Reachability can only be computed on one vertex at a time. To
# get graph-wide statistics, change the value of "vertex"
# manually or write a for loop. (Remember that, unlike R objects,
# igraph objects are numbered from 0.)

ok, so when ever using igraph, the first roll/column is 0 other than 1, but matrix starts at 1, thus for any calculation under igraph, you would need x-1, shown at

this_node_reach <- subcomponent(g, (i - 1), mode = m)

but for the alter calculation, there is a typo here

alter = this_node_reach[j] + 1

delete +1 and it will work alright

answered Mar 5, 2013 at 14:23

YangJ's user avatar

YangJYangJ

532 silver badges6 bronze badges

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

Last Updated :
18 Mar, 2022

Like Article

Save Article

Понравилась статья? Поделить с друзьями:
  • Subaru impreza ошибка p2109
  • Sub or function not defined vba excel ошибка
  • Subor гироскутер ошибки
  • Subaru forester ошибка p0700
  • Subnautica ошибка unity 2019