Number of items to replace is not a multiple of the length of the substitute

Asked

Viewed 1,070 times

2

I am trying to create a method for the Minkowsky formula but it is giving this error. It happens in the line where I try to assign the value to matriz_distancia[i,j].

distancia_minkowsky <- function(xtreinamento, xteste, r){
  matriz_distancia <- matrix(0, nrow(xteste), ncol = nrow(xtreinamento))
  for(i in 1:nrow(xtest)){
    for(j in 1:nrow(xtreinamento)){
      matriz_distancia[i,j] <- (abs(xteste[i,] - xtreinamento[j,])^r)^(1/r)
    }
  }
  return(matriz_distancia)
}

I had tried differently, doing matriz_distancia[i,] <- formula, but at each iteration a whole new line was generated at the i position For example, in the first iteration of the internal loop generates this, for j = 10

4.680581 0.4122082 4.680581 0.4122082 4.680581 0.4122082 4.680581 0.4122082 4.680581 0.4122082

In the second iteration generates this:

0.8917289 0.377533 0.8917289 0.377533 0.8917289 0.377533 0.8917289 0.377533 0.8917289 0.377533

I don’t understand why this happens, I’m not familiar with R. It’s generating repeated values

1 answer

4


In doing

matriz_distancia[i,j] <- (abs(xteste[i,] - xtreinamento[j,])^r)^(1/r)

you are trying to put a vector, which is the result of the formula

(abs(xteste[i,] - xtreinamento[j,])^r)^(1/r)

within a position dedicated to a number:

matriz_distancia[i,j]

A distance in a metric space is always a real number greater than or equal to zero. Therefore, your formula is incomplete. Missing add the sum of Minkowski distance. The code below solves this problem:

distancia_minkowsky <- function(xtreinamento, xteste, r){
matriz_distancia <- matrix(0, nrow=nrow(xteste), ncol=nrow(xtreinamento))
  for(i in 1:nrow(xteste)){
      for(j in 1:nrow(xtreinamento)){
          matriz_distancia[i,j] <- sum(abs(xteste[i, ] - xtreinamento[j, ])^r)^(1/r)
      }
  }
  return(matriz_distancia)
}
  • Thank you so much! You helped so much :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.