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

2

I'm trying to create a method for the minkowsky formula but it's giving this error. It happens on 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 it the other way, doing matriz_distancia[i,] <- formula , but at each iteration a whole new line was generated in position i For example, in the first iteration of the inner 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 it generates this:

  

0.8917289   0.377533   0.8917289   0.377533   0.8917289   0.377533   0.8917289   0.377533   0.8917289   0.377533

I do not understand why this happens, I'm not familiar with R. You are generating repeated values

    
asked by anonymous 08.06.2017 / 01:25

1 answer

4

When 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. So your formula is incomplete. He missed adding the sum of Minkowski's distance. The code below addresses 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)
}
    
08.06.2017 / 14:14