R - getting the highest value for each ID

Viewed 52

I've the following df:

>> animals_df:

animal_name    age
cat             1
cat             1
cat             2
cat             3
cat             3
dog             1
dog             1
dog             3
dog             4
dog             4
dog             4
horse           1
horse           3
horse           5
horse           5
horse           5

I want to extract only the animals with highest age from each species. So I want to get the following output:

animal_name    age
    cat         3
    cat         3
    dog         4
    dog         4
    dog         4
    horse       5
    horse       5
    horse       5

I've tried using:

animals_df = do.call(rbind,lapply(split(animals_df, animals_df$animal_name), function(x) tail(x, 1) ) )

But this will only give one instance of each animal which is the following:

animals_name    age
    cat          3
    dog          4
    horse        5
2 Answers
Related