Jacob Myer
Jacob Myer

Reputation: 509

"subscript out of bounds" could the column name be causing this issue?

I am trying to plot segments that connect the points in coordinates, this is what my plot.mst() function is trying to accomplish. I haven't been able to see if that function works properly because when I run this code I receive the error message

"Error in arcList[i, 1] : subscript out of bounds"

Yet I am not sure why this is occurring.

I thought it might have something to do with the column name, so I changed arcList[i,1] to arclist[i] which sort-of solved it but now the error is in the next line as you see below. I tried double brackets and single there as well and neither has helped.

How can I handle or avoid this error?

n = 50
x = round(runif(n)*1000)
y = round(runif(n)*1000) 
coordinates = cbind(x,y)
d = as.matrix(dist(coordinates))

AdjMatrix2List = function(d) {
  indices = which(!is.na(d), arr.ind = TRUE)
  ds = cbind(indices[,2], indices[,1], d[indices])
  colnames(ds) = c("head", "tail", "weight")
  return(ds)
}

ds = AdjMatrix2List(d)
ds.mst = msTreePrim(1:n,ds)

#Examine ds.mst$tree.arcs
str(ds.mst$tree.arcs)
 num [1:49, 1:3] 1 29 1 28 30 6 6 9 27 21 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:3] "ept1" "ept2" "weight"

plot.mst = function(arcList) {
  for (i in seq_along(arcList))
    start = arcList[i]
    end = arcList[i,2]
    segments(coordinates(start,1), coordinates(start,2), coordinates(end,1), coordinates(end,2))
}

plot(x,y,pch=16)
plot.mst(ds.mst$tree.arcs)

> *Error in arcList[[i, 2]] : subscript out of bounds*

Upvotes: 0

Views: 494

Answers (1)

Roland
Roland

Reputation: 132576

m <- matrix(1:4, ncol = 2)
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4

seq_along(m)
#[1] 1 2 3 4
#treats m as a vector

for (i in seq_along(m)) print(m[i])
#[1] 1
#[1] 2
#[1] 3
#[1] 4
#works but subsets m as a vector

for (i in seq_along(m)) print(m[i, 2])
#[1] 3
#[1] 4
#Error in m[i, 2] : subscript out of bounds
#matrix subsetting, there are only two rows, but i becomes larger than 2

for (i in seq_len(nrow(m))) print(m[i, 2])
#[1] 3
#[1] 4
#works and subsets m as a matrix

Upvotes: 2

Related Questions