Thursday, 15 August 2013

r - How to build a function to return the minimum distance to [-1,0,1]? -



r - How to build a function to return the minimum distance to [-1,0,1]? -

i have real vector in interval (-1,1), example:

v = [ 0.999 0.0003 0.34 -0,95 0.63 -0.0001 0.82]

i want build function fmindistance() in r homecoming vector of indexes of elements of vector v such distances these elements -1 or 0 or 1 minimum.

fmindistance <- function(vector, k){ ......code ........ }

for example:

v = [ 0.999 0.0003 0.34 -0,95 0.63 -0.0001 0.82] , k = 3, so:

result = [ 1 2 6]

if understand correctly, function should work

v<- c(0.999, 0.0003, 0.34, -0.95, 0.63, -0.0001, 0.82) fmindistance <- function(x, targets=c(-1,0,1), k=3) { r<- order(sapply(x, function(z) min(abs(z - targets)))) sort(r[1:k]) } fmindistance(v) #[1] 1 2 6

this find closest points 1 of targets. homecoming 3 closest in index order.

r

No comments:

Post a Comment