Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in R Programming by (4k points)
edited by

There is an error of subscript out of bounds:

    # 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))
    # Calculate reachability for each vertix
    reachability <- function(f, n) {
    reach_mat = matrix(nrow = vcount(f),
    ncol = vcount(f))
    for (i in 1:vcount(f)) {
    reach_mat[i,] = 0
    this_node_reach <- subcomponent(f, (i - 1), mode = n)
    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

This is showing an error Error in reach_mat[i, alter] = 1 : subscript out of bounds

So my question is:

  • Can someone define me what is  subscript-out-of-bounds error and what's the cause behind it?

  • How to sort out this type of error in a generic way?

1 Answer

0 votes
by (107k points)

Your code is throwing the error because you are accessing an array that is out of its boundary.

The following are the steps to debug such errors.

First set the options(error=recover)

Then run reach_full_in <- reachability(krack_full, 'in'). You will 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")

If you enter 1, then will get:

 Called from: top level 

After that, type ls() to see the current variables:

  1] "*tmp*"           "alter"           "g"               

     "i"               "j"                     "m"              

    "reach_mat"       "this_node_reach"

Now, you will able to observe the dimension of the 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 handle such errors in R programming, I would recommend the following steps:

  1. Try to use applyxx function. They are safer than for loop.
  2. Use seq_along and not 1:n (1:0).
  3. Try to avoid mat[i,j] index access.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...