0

I know that to retrieve the closest value to 0, I could use the following:

filter(abs(x-0)==min(abs(x-0)))

...with x being your vector. How do I retrieve the closest two values to 0?

Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
RobertP.
  • 213
  • 1
  • 12

3 Answers3

1
tt <- sample(-200:200, 20)
tt[order(abs(tt), decreasing = F)][1:2]

Like that?

brandonEm
  • 316
  • 1
  • 8
1

Can't you just use sort()?

set.seed(1)
x <- rnorm(10)
sort(abs(x-0))[1:2]
#> [1] 0.1836433 0.3053884

Created on 2019-01-28 by the reprex package (v0.2.1)

I also don't think the -0 does anything for you so could just do abs(x).

Chase
  • 67,710
  • 18
  • 144
  • 161
  • Thank to both of you! Both your solutions works - though I'd need to use it within `dplyr` because I will need the two closest values to 0 in each of my conditions. (sorry, that was not mentioned in the question). – RobertP. Jan 29 '19 at 02:15
  • @RobertP. - if you modify your question to more accurately reflect your use case, you'll get more tailored answers. See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for tips. – Chase Jan 29 '19 at 02:27
1

Here's a dplyr version; you can use top_n to get the n smallest (or largest) values for some field:

df = data.frame(x = runif(100, -1, 1))

df %>%
  mutate(dist.from.0 = abs(x - 0)) %>%
  top_n(-2, dist.from.0)
A. S. K.
  • 2,504
  • 13
  • 22