match - r-find two closet values in a vector -


i tried find 2 values in following vector, close 10. expected value 10.12099196 , 10.63054170. inputs appreciated.

 [1]  0.98799517  1.09055728  1.20383713  1.32927166  1.46857509  1.62380423  1.79743107  1.99241551  2.21226576  2.46106916  2.74346924  3.06455219  3.42958354  3.84350238  4.31005838 [16]  4.83051356  5.40199462  6.01590035  6.65715769  7.30532785  7.93823621  8.53773241  9.09570538  9.61755743 10.12099196 10.63018180 11.16783243 11.74870531 12.37719092 13.04922392 [31] 13.75661322 14.49087793 15.24414627 16.00601247 16.75709565 17.46236358 18.06882072 18.51050094 18.71908344 18.63563523 18.22123225 17.46709279 16.40246292 15.09417699 13.63404124 [46] 12.11854915 10.63054170  9.22947285  7.95056000  6.80923943  5.80717982  4.93764782  4.18947450  3.54966795  3.00499094  2.54283599  2.15165780  1.82114213  1.54222565  1.30703661 [61]  1.10879707  0.94170986  0.80084308  0.68201911  0.58171175  0.49695298  0.42525021  0.36451350  0.31299262  0.26922281  0.23197860  0.20023468  0.17313291  0.14995459  0.13009730 [76]  0.11305559  0.09840485  0.08578789  0.07490387  0.06549894  0.05735864  

i can't think of way without using sort. however, can speed using partial sort.

x[abs(x-10) %in% sort(abs(x-10), partial=1:2)[1:2]] # [1]  9.617557 10.120992 

in case same values present more once, you'll of them here. so, can either wrap unique or can use match instead follows:

x[match(sort(abs(x-10), partial=1:2)[1:2], abs(x-10))] # [1] 10.120992  9.617557 

dput output:

dput(x) c(0.98799517, 1.09055728, 1.20383713, 1.32927166, 1.46857509,  1.62380423, 1.79743107, 1.99241551, 2.21226576, 2.46106916, 2.74346924,  3.06455219, 3.42958354, 3.84350238, 4.31005838, 4.83051356, 5.40199462,  6.01590035, 6.65715769, 7.30532785, 7.93823621, 8.53773241, 9.09570538,  9.61755743, 10.12099196, 10.6301818, 11.16783243, 11.74870531,  12.37719092, 13.04922392, 13.75661322, 14.49087793, 15.24414627,  16.00601247, 16.75709565, 17.46236358, 18.06882072, 18.51050094,  18.71908344, 18.63563523, 18.22123225, 17.46709279, 16.40246292,  15.09417699, 13.63404124, 12.11854915, 10.6305417, 9.22947285,  7.95056, 6.80923943, 5.80717982, 4.93764782, 4.1894745, 3.54966795,  3.00499094, 2.54283599, 2.1516578, 1.82114213, 1.54222565, 1.30703661,  1.10879707, 0.94170986, 0.80084308, 0.68201911, 0.58171175, 0.49695298,  0.42525021, 0.3645135, 0.31299262, 0.26922281, 0.2319786, 0.20023468,  0.17313291, 0.14995459, 0.1300973, 0.11305559, 0.09840485, 0.08578789,  0.07490387, 0.06549894, 0.05735864) 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -