Reputation: 35
Lets say I have a vector of 10 numbers, i.e a<-(1:10)
I want a function where I can give an index, and then it returns the 4 "closest" elements.
In this case:
f(4) = c(2,3,5,6)
f(2) = c(10,1,3,4)
Note that the original vector could be anything, so if a <- c(10,2,6,4,7,9,1)
f(2) = c(1,10,6,4)
f(5) = c(3,4,9,1)
Upvotes: 1
Views: 58
Reputation: 51998
The natural way to do this is with modular arithmetic. This is a case in which R's 1-based indexing is mildly annoying. It is best to subtract 1 from the index, use modular arithmetic to get the 0-based indices that you would want, and then add 1 to get back to 1-based:
f <- function(v,i){
m <- length(v)
j <- i-1
indices <- 1 + c(j-2,j-1,j+1,j+2) %% m
v[indices]
}
#test:
a <- c(10,2,6,4,7,9,1)
print(f(a,2))
print(f(a,5))
Output:
[1] 1 10 6 4
[1] 6 4 9 1
Upvotes: 3