如何解决"下标越界错误"

时间:2014-10-24 04:40:17

标签: r

我有一个R代码应用于某些数据X和Y,代码相当简单,但它给出了一定的错误

"Error in `[<-`(`*tmp*`, R, , value = c(1, 1)) : subscript out of bounds"

任何人都可以帮我解决一下。

#X <- read.table("data1.dat")
#Y <-read.table("data2.dat")

X <- c(1,2,43,1,6,5,44,6.8,7.8,9.8)
Y <- c(1,3,31,26,78,4,5,44,4,6)

length(X)
length(Y)

Rmax <- 15
data_len <- length(X)
Z <- as.matrix(cbind(X,Y))
Cen <- matrix(rnorm(2*Rmax),Rmax,2)
Xe <- as.matrix(cbind(1,X))
w <-  matrix(rnorm(2*Rmax),Rmax,2)
lambda <- matrix(rnorm(1*Rmax),Rmax,1)
U <- matrix(rnorm(1*Rmax),Rmax,1)
gamma <- matrix(rnorm(2*Rmax),Rmax,2)
P_matrix <- 10^3*matrix(rnorm(2*2),2,2)
Yhat <- matrix(,data_len,1)
a1 <- 0
a2 <- 0
a4 <- matrix(rnorm(2),1,2)
a3 <- 0
Pz <- 0
P <- matrix(rnorm(1*Rmax),Rmax,1)
dist <- numeric(Rmax)
r <- 0.04
m3 <- 0
k <- 1

while (k < length(X)){  
 if(k == 1){  
 Cen[1,] <- Z[k,]; U[k,] <- 1; lambda <- matrix(sapply(U,function(x){x/sum

(U)}),Rmax,1); Yhat[k,] <- Xe[k,]%*%(t(w)%*%lambda)

} else {

a1 <- big_V(Z[k,]);a2 <- a2+ big_V(Z[k-1,]);a4 <- a4 + Z[k-1,];a3 <- sum(Z[k,]*a4)

B <- ((k-1)*(a1+1))+a2-(2*a3); Pz <- (k-1)/B

for(i in 1:length(P)){
    P[i] <- ((k-1)*P[i])/((k-2)+(P[i])+(P[i])*(dist(Z[k-1,],Z[k,])))
}
print(k)
for (i in 1:Rmax){
 dist[i] <- abs(sqrt(sum((Z[k,]-Cen[i,])^2)))
}

p1 <- min(dist)
p2 <- which.min(dist)

m1 <- max(P)
m2 <- which.max(P)
m3 <- (p1/r)+(Pz/m1)

if (Pz > m1 & m3 < 1){
Cen[m2,] <- Z[k,]
P[m2] <- Pz
}


for (i in 1:Rmax){
U[i] <- exp(-r*(abs(sqrt(sum((X[k,]-Cen[i,1])^2)))))
}

lambda <- sapply(U, function(x) x/sum(U)) 

P_matrix <- (diag(2)-(t(gamma)%*%lambda%*%Xe[k,]))%*%P_matrix

A <- lambda%*%Xe[k,]
Z1 <- P_matrix%*%t(A)
Z2 <- A%*%P_matrix%*%t(A)
Z3 <- diag(15)+Z2
gamma <- t(Z1%*%solve(Z3))


w_bar <- Xe[1,]%*%t(w)%*%lambda
w <-  w + (gamma*diag(e))

}  
} 
Yhat <- Xe%*%t(w)%*%lambda

我缩短了数据以便快速计算。

1 个答案:

答案 0 :(得分:0)

我不确定你到底要做什么。但是,当R变得大于15时会发生错误(因为Cen是仅包含15行的矩阵)。请检查以下几行:

Rmax <- 15
Cen <- matrix(rnorm(2*Rmax),Rmax,2)

while (k < length(X)){  
 if(k == 1){  
R <- R+1; 
Cen[R,] <- Z[k,];  **error**

您逐步增加R。如果未定义R=16Cen[16,]