Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - What is the best way to find the index of two vectors whose values are closest to a 2D point

I will try to explain my goal the best way possible.

Let's say I have two vectors:

Teffs <- c(6000, 6100, 6200, ..., 7500)
Ls <- c(40, 41, 42, 43, 44, ..., 60)

I want to find what elements in the vectors give values closest to the point (6199, 42.1). The index of Teffs MUST be the same as the index in Ls, otherwise I could easily index each vector individually using something like:

values <- c(6199, 42.1)
indexa <- which.min(abs(Teffs - values[1]))
indexb <- which.min(abs(Ls - values[2]))
indexa
3
indexb
3

In this scenario, it is obvious the third elements in the vector give the closest values to the desired point. However, what if it was more ambigous? What if the point I wanted to find indices closest to was (6200, 62) or (6800, 59) or even (6000, 60)? How would I go about this while maintaining that the index in Teffs is the same as in Ls?

question from:https://stackoverflow.com/questions/65946559/what-is-the-best-way-to-find-the-index-of-two-vectors-whose-values-are-closest-t

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

1 Reply

0 votes
by (71.8m points)

Since the scales are different (L, log10 and Teff, linear), this should work:

Teff <- c(6000, 6100, 6200, 7500)
L <- c(40, 41, 42, 43)
dst <- sqrt((log10(Teff) - log10(6199))^2 + (L - 42.1)^2)
which.min(dst)
# [1] 3

This adjusts the scales but the range of each variable could still be a problem since L about 10 times larger than log10(Teff). That might suggest using L/10.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...