Subscript out of bounds - general definition and solution?
This is because you try to access an array out of its boundary.
I will show you how you can debug such errors.
- I set
options(error=recover)
-
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")
-
I enter 1 and I get
Called from: top level
-
I type
ls()
to see my current variables1] "*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 thanfor
- I use
seq_along
and not1: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])
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.