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?
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)
.
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)