Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

r - Minimizing average distance

I am working on a function that can give a vector a, find a set of values b where the average distance of values in a to the closest value in b is minimal. In other words, I want to find the ideal spread for a fixed number of points across a distribution, so the average distance is minimal. I hope this explanation makes sense to people.

The function below accepts two arguments: the vector a and p which is the length of b. It works as intended for p = 2, but produces an error for any larger number of p (See the error below). The error makes no sense to me as it should not be possible that the two vectors have different lengths. (mc)lapply running Closest over the vector a should always produce a vector of the same length as a so I have no clue how to fix this issue.

library(DescTools)
library(stats)
library(parallel)

party_opt <- function(a, p) {
dist_f <- function(a, b) {
  dist <- mean(abs(a - unlist(mclapply(a, function(i) Closest(x = b, a = i)), use.names=FALSE)))
  return(dist)
}
out <- optim(par = rep(min(a),p), fn = dist_f,  a = a)
return(out)
}

This is the error that occurs with more than two values.

Warning messages:

1: In people - unlist(mclapply(a, function(i) Closest(x = b, a = i)), : longer object length is not a multiple of shorter object length


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...