r - Finding the K closest points of a vector to a separate point in Rstudio -


say have vector x consisting of points such (1,4,5,6,3,2,5,7,8,44,3,7) , need want find k=2 points of closest 6.4 meaning 6 , 7 there function in , if not best way in r?

to make function then,

fun1 <- function(vec, val, k){             vec[order(abs(vec-val))][seq_len(k)]            }  fun1(x, 6.4, 2) #[1] 6 7 fun1(x, 6.4, 3) #[1] 6 7 7 fun1(x, 5, 4) #[1] 5 5 4 6 

to unique values add unique,

fun1 <- function(vec, val, k){           unique(vec[order(abs(vec-val))])[seq_len(k)]           } fun1(x, 6.4, 3) #[1] 6 7 5 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -