【发布时间】: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