"number of items to replace is not a multiple of replacement length"错误消息



我收到错误消息"dist.mat[j, i] <- d 中的错误: 当我运行脚本时,要替换的项目数不是替换长度的倍数":

 uncenter.distance <- function(X) {
   n <- nrow(X)
   dist.mat <- matrix(0, n, n)
   xj <- X[1,]
   for (i in 1:n) {
     for (j in 1:n) {
       yj <- X[j,]
       d <- 1 - sum(xj %*% yj) / sqrt((xj)^2 * (yj)^2)
       dist.mat[j,i] <- d
       dist.mat[i,j] <- d
      }
      xj <- X[1+i,]
    }
    return(dist.mat)
 }

sqrt((xj)^2 * (yj)^2)返回长度为n的向量,因此d也是长度n的向量,dist.mat[j,i]期望单个值,这就是为什么dist.mat[j,i] <- d不能工作的原因。您是否忘记对平方根的部分求和(或平均值或任何返回长度为 1 向量的函数(?

在分配 xj 之前,您还需要添加一个 if,以防 i=n(1+n 行不存在(

uncenter.distance <- function(X) {
  n <- nrow(X)
  dist.mat <- matrix(0, n, n)
  xj <- X[1,]
  for (i in 1:n) {
    for (j in 1:n) {
     yj <- X[j,]
     # I put a sum inside the sqrt 
     # you can change it to what you meant to do
     d <- 1 - sum(xj %*% yj) / sqrt(sum((xj)^2 * (yj)^2))
     dist.mat[j,i] <- d
     dist.mat[i,j] <- d
    }
    # add an if statement for last column
    if (i<n){
      xj <- X[1+i,]
    }
  }
  return(dist.mat)
}
uncenter.distance(matrix(1:4,nrow=2))

它现在运行:

 > uncenter.distance(matrix(1:6,nrow=2))
           [,1]       [,2]
[1,] -0.3163105 -0.3591645
[2,] -0.3591645 -0.4142136

相关内容

最新更新