There are a few ways to do this.
Here's a dplyr
solution (found using this answer):
a %>%
group_by(id) %>%
slice(which.min(abs(b - 1.43)))
id b
<chr> <dbl>
1 A 1.5
2 B 1.4
Here's a base solution:
do.call('rbind', by(a, a$id, function(x) x[which.min(abs(x$b - 1.43)), ]))
id b
<chr> <dbl>
1 A 1.5
2 B 1.4
Here's a hacky dplyr
solution:
a %>%
mutate(AbsDiff = abs(b - 1.43)) %>%
group_by(id) %>%
mutate(AbsDiff_r = rank(AbsDiff, ties.method = 'first')) %>%
filter(AbsDiff_r == 1)
id b AbsDiff AbsDiff_r
<chr> <dbl> <dbl> <int>
1 A 1.5 0.07 1
2 B 1.4 0.03 1