【问题标题】:having the error message "number of items to replace is not a multiple of replacement length"出现错误消息“要替换的项目数不是替换长度的倍数”
【发布时间】:2019-06-20 09:46:28
【问题描述】:

我收到错误消息“dist.mat[j, i]

 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] &lt;- d不能工作的原因.您是否忘记将部分与平方根相加?
  • 出现新错误:X[1, ] 中的错误:“闭包”类型的对象不是子集

标签: r


【解决方案1】:

sqrt((xj)^2 * (yj)^2) 返回一个长度为n 的向量,因此d 也是一个长度为n 的向量,dist.mat[j,i] 需要一个值,这就是dist.mat[j,i] &lt;- 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

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多