【问题标题】:R: "Subscript out of bounds" error on functionR:函数上的“下标越界”错误
【发布时间】:2014-03-20 04:00:40
【问题描述】:

我的函数继续出现错误,可能是我忽略了一些简单的事情。应用函数时,我无法运行代码而不会出错。

k.nn <- function(k,p1,p) {                          
k > 0                           
K <-length(k)                               
p=matrix()                                      

for (i in p) {                                             
matrix <- cbind(p,p1[1],p1[2])                  
d <- sqrt((matrix[,1]-matrix[,3])^2+(matrix[,2]-matrix[,4])^2)  
}

##use the sort function to find the smallest distance from 1:k and return all nearest k values
sort.d <- function(x) {                             #implement bubble sort      
N=length(x)                                     
N>0                                                  
c=class(x)                                      
for (n in length(x):2) {                            #distinguish the last term in the vector, name it, much be of x length, consists an error of length 1. Error if you compute n in length(x):1, cover length of 1
if(length(x)<2) 
return(x)
 for (m in 1:(n - 1)) {                             #distinguish the first term in the vector, name it
 if(x[m]>x[m + 1]) {                            #begin comparing each term to neighboring term
swap<-x[m]                                      
x[m]<-x[m + 1]          
x[m + 1]<-swap  
}
}
}
return(x)                                       
}

sorted=sort.d(d)                                    

 for (n in k){
 print(sorted[1:k])}                            
 }
 p=matrix(c(6.9,7.6,7.1,.4,6.2,1.8,2.5,2.3,5.7,6.9,.9,4.4,5.2,1.9,.6,7.4,1.2,6.6,3.3,4.9),nrow=10,ncol=2) #given matrix
p1=c(6,6)                                       
k=3                                         nn.3=k.nn(k,p1,p)                                   
print(nn.3)

【问题讨论】:

  • 没有reproducible example,我无法告诉你哪里出了问题。
  • @BlueMagister 请查看编辑。我会在您查看后将其删除,因为这是针对课程的。我正在寻找指导,可能我遗漏了什么。
  • 防止该帖子被删除的唯一方法是对答案进行投票。

标签: r function for-loop


【解决方案1】:

缺少回车符或“;”在引发错误的倒数第二行中。如果您删除最后一行以便可以使用traceback(),它会告诉您当矩阵索引为 4 时 k.nn 会引发“下标越界”错误。

调试 101 告诉您放入打印函数以查看函数失败的位置并在之后放入打印

        c=class(x)     ; print(c)              

... 给你一个结果,但是在sort.d 函数中放置另一个结果不会被执行。从那一点看上游的代码,我们看到:

 d <- sqrt((matrix[,1]-matrix[,3])^2+(matrix[,2]-matrix[,4])^2)  

所以看看你给出的函数和矩阵,......我猜你将一个两列矩阵传递给一个需要四列参数的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 2015-02-11
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多