Improving distance calculation

南楼画角 提交于 2019-12-12 03:27:53

问题


I have build my own distance (let's call it d1). Now, I have a matrix for which I need to compute the distance. Considering x as the matrix with the content for each sample, the code written to get the distance matrix is the following:

# Build the matrix
  wDM <- matrix(0, nrow=nrow(x), ncol=nrow(x))

# Fill the matrix
  for (i in 1:(nrow(wDM)-1)){
    for (j in (i+1):nrow(wDM)){

    wDM[i,j] <- wDM[j,i] <- d1(x[i,], x[j,])

  }
}

I have to implement this process several times. So, I was wondering if there is a faster way to fill the distance matrix wDM rather than using two for loops.

Thank you so much,


回答1:


You can use dist() from proxy package. It lets you specify user-defined distance function by setting the parameter method = #yourDistance default would be euclidean. Check the documentation here: https://cran.r-project.org/web/packages/proxy/proxy.pdf



来源:https://stackoverflow.com/questions/45231861/improving-distance-calculation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!