How to filter lines in R?

Asked

Viewed 495 times

0

Good afternoon!
I have the following data:

1. Animal1 128kg  
2. Animal1 150kg  
3. Animal1 80kg  
4. Animal2 169kg  
5. Animal2 113kg  

How do I filter for each animal the weight closer to 120kg and erase the lines?
- As a result I would have only lines 1 and 5.

1 answer

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.