【问题标题】:"subscript out of bounds" could the column name be causing this issue?“下标越界”列名是否会导致此问题?
【发布时间】:2019-09-25 14:20:57
【问题描述】:

我正在尝试绘制连接coordinates 中的点的线段,这就是我的plot.mst() 函数试图完成的任务。我无法查看该功能是否正常工作,因为当我运行此代码时,我收到错误消息

“arcList[i, 1] 中的错误:下标越界”

但我不确定为什么会发生这种情况。

我认为这可能与列名有关,所以我将 arcList[i,1] 更改为 arclist[i] 解决了它,但现在错误出现在下一行,如下所示。我也尝试过双括号和单括号,但都没有帮助。

如何处理或避免此错误?

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*

【问题讨论】:

  • 请给str(ds.mst$tree.arcs),这样我们就可以看到arcList实际上有什么结构。
  • @Bernhard 我编辑了我的问题并添加了str(ds.mst$tree.arcs)
  • 好的,那么arcList 不是列表而是矩阵。 seq_along 将使 forloop 循环 49*3 次,而 arcList 只有 49 行。 arcList[i,2] 的语法没问题,但 i 会变大,即“越界”。而不是for (i in seq_along(arcList)) 尝试for (i in 1:nrow(arcList))

标签: r


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多