Here are three ways to do what the question asks, two on R basis and one with the package dplyr
.
1. aggregate
.
aggregate(Peso ~ Animal, dados, FUN = function(x) x[which.min(abs(x - 120))])
# Animal Peso
#1 Animal1 128
#2 Animal2 113
2. tapply
.
p <- with(dados, tapply(Peso, Animal, function(x) x[which.min(abs(x - 120))]))
dados[dados$Peso %in% p & dados$Animal %in% names(p), ]
# Animal Peso
#1 Animal1 128
#5 Animal2 113
3. Package dplyr
.
library(dplyr)
dados %>%
mutate(Diff = abs(Peso - 120)) %>%
group_by(Animal) %>%
summarise(Peso = Peso[which.min(Diff)])
## A tibble: 2 x 2
# Animal Peso
# <fct> <dbl>
#1 Animal1 128
#2 Animal2 113
Thanks for your help!
– Débora Morales