gpt4 book ai didi

R - 获取每个 ID 的最高值

转载 作者:行者123 更新时间:2023-12-04 09:42:40 24 4
gpt4 key购买 nike

我有以下 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

我只想从每个物种中提取年龄最大的动物。所以我想得到以下输出:

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

我试过使用:

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

但这只会给出每种动物的一个实例,如下所示:

animals_name    age
cat 3
dog 4
horse 5

最佳答案

使用 dplyr/tidyverse 很容易:

library(tidyverse)

# How I read your data in, ignore since you already have your data available
df = read.table(file="clipboard", header=TRUE)
df %>%
group_by(animal_name) %>%
filter(age == max(age))

# Output:
Source: local data frame [8 x 2]
Groups: animal_name [3]

animal_name age
<fctr> <int>
1 cat 3
2 cat 3
3 dog 4
4 dog 4
5 dog 4
6 horse 5
7 horse 5
8 horse 5

关于R - 获取每个 ID 的最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com