Jdan
Jdan

Reputation: 149

Find the Closest value from vector of Polar coordinates

I'm assuming there is a very simple solution to my problem where I have a vector that represents polar angles(i.e. 1 to 360 degrees).

x<-seq(300,340)

I need to find the value of x closest to y,

y<-30

In this example I need to have 340 returned from x I am aware of the Closest function from the DescTools package which would return 300 from x. I'm sure the answer is probably very simple but it is eluding me.

Thoughts welcome

Upvotes: 0

Views: 81

Answers (1)

steveLangsford
steveLangsford

Reputation: 646

Does this do what you want?

x <- 300:340
y <- 30

polardist <- sapply(x,function(x){min((y-x)%%360,(x-y)%%360)})
ans <- x[polardist==min(polardist)] #Will have length>1 if there are ties

Upvotes: 1

Related Questions