0
votes

I get the error message "Error in dist.mat[j, i] <- d : number of items to replace is not a multiple of replacement length" when I run the script:

 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)
 }
1
sqrt((xj)^2 * (yj)^2)returns a vector of length n, thus d is also a vector of length n, dist.mat[j,i] expects a single value, that is why dist.mat[j,i] <- d cannot work. Did you forget to sum the part with the square root ? - fmarm
Getting new error: Error in X[1, ] : object of type 'closure' is not subsettable - nicksiz

1 Answers

0
votes

sqrt((xj)^2 * (yj)^2) returns a vector of length n, thus d is also a vector of length n, dist.mat[j,i] expects a single value, that is why dist.mat[j,i] <- d cannot work. Did you forget to sum (or mean or whatever function that returns a length 1 vector) the part with the square root ?

You also need to add an if before assigning xj, in case i=n (1+n row does not exist)

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))

It runs now :

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