在使用R时,我经常收到错误消息“下标超出界限”。For example
# 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))
# convert to graph data farme
krack_full <- graph.data.frame(krack_full_nonzero_edges)
# 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])
}
}
# Calculate reachability for each vertix
reachability <- function(g, m) {
reach_mat = matrix(nrow = vcount(g),
ncol = vcount(g))
for (i in 1:vcount(g)) {
reach_mat[i,] = 0
this_node_reach <- subcomponent(g, (i - 1), mode = m)
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 <- reachability(krack_full, 'in')
reach_full_in这将生成以下错误Error in reach_mat[i, alter] = 1 : subscript out of bounds。
然而,我的问题并不是关于这段特定的代码(尽管解决这个问题也会有帮助),但我的问题更笼统:
发布于 2013-02-22 19:16:08
这是因为您试图访问超出其边界的数组。
我将向您展示如何调试这些错误。
options(error=recover)reach_full_in <- reachability(krack_full, 'in')我得到:
reach_full_in <-可达性(krack_full,' in ')错误在reach_mati中,alter = 1:下标超出界限输入一个帧号,或0退出1:可达性(krack_full,"in")ls()以查看当前变量
1] "*tmp*“”更改"g“i”"j“"m”"reach_mat“"this_node_reach”现在,我将看到我的变量的维度:
Browse[1]> i
[1] 1
Browse[1]> j
[1] 21
Browse[1]> alter
[1] 22
Browse[1]> dim(reach_mat)
[1] 21 21你看,那个圣坛是越界的。22 > 21。在队伍中:
reach_mat[i, alter] = 1为了避免这样的错误,我个人这样做:
applyxx函数。他们比for更安全seq_along而不是1:n (1:0)mat[i,j]索引访问,请尝试在向量化解决方案中进行思考。编辑矢量化解决方案
例如,我在这里看到,您没有使用set.vertex.attribute是向量化的事实。
你可以替换:
# 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])
}
}通过这一点:
## 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])发布于 2013-02-22 19:07:00
它仅仅意味着alter > ncol( reach_mat )或i > nrow( reach_mat ),换句话说,您的索引超过了数组边界(i大于行数,或者alter大于列数)。
只需运行上面的测试,看看发生了什么和什么时候。
发布于 2017-08-22 20:31:53
只添加了上述响应:在这种情况下,有一种可能是您正在调用一个对象,但由于某种原因,您的查询无法使用该对象。例如,您可以按行名或列名子集,当所请求的行或列不再是数据矩阵或数据帧的一部分时,您将收到此错误消息。解决方案:作为上述响应的简短版本:您需要找到最后一个工作行名称或列名,下一个被调用的对象应该是找不到的对象。如果您运行类似于"foreach“的并行代码,那么您需要将代码转换为for循环,以便能够对其进行故障排除。
https://stackoverflow.com/questions/15031338
复制相似问题