使用group by获取另一列最大值对应的值
Using group by to get the value corresponding to the max value of another column
在我的数据集中,受访者被分组在一起,并且有关于他们年龄的可用数据。我希望同组的所有人都拥有该组中最老的人的价值。
所以我的示例数据如下所示。
df <- data.frame(groups = c(1,1,1,2,2,2,3,3,3),
age = c(12, 23, 34, 13, 24, 35, 13, 25, 36),
value = c(1, 2, 3, 4, 5, 6, 7, 8, 9))
> df
groups age value
1 1 12 1
2 1 23 2
3 1 34 3
4 2 13 4
5 2 24 5
6 2 35 6
7 3 13 7
8 3 25 8
9 3 36 9
我希望它看起来像这样
> df
groups age value new_value
1 1 12 1 3
2 1 23 2 3
3 1 34 3 3
4 2 13 4 6
5 2 24 5 6
6 2 35 6 6
7 3 13 7 9
8 3 25 8 9
9 3 36 9 9
知道如何使用 dplyr 做到这一点吗?
我试过类似的方法,但没有用
df %>%
group_by(groups) %>%
mutate(new_value = df$value[which.max(df$age)])
预先,“从不”(好的,几乎从不)在 dplyr 管道中使用 df$
。在这种情况下,df$value[which.max(df$age)]
每次都引用 original 数据,而不是 grouped 数据。在此数据集中的每个组中,value
的长度为 3,而 df$value
的长度为 9。
我觉得唯一适合在管道内使用 df$
(引用当前数据集的原始值)的时候是需要查看管道前数据的时候,在 任何分组、重新排序或在当前保存的(流水线前)版本 df
之外创建的新变量的情况下。
dplyr
library(dplyr)
df %>%
group_by(groups) %>%
mutate(new_value = value[which.max(age)]) %>%
ungroup()
# # A tibble: 9 x 4
# groups age value new_value
# <dbl> <dbl> <dbl> <dbl>
# 1 1 12 1 3
# 2 1 23 2 3
# 3 1 34 3 3
# 4 2 13 4 6
# 5 2 24 5 6
# 6 2 35 6 6
# 7 3 13 7 9
# 8 3 25 8 9
# 9 3 36 9 9
data.table
library(data.table)
DT <- as.data.table(df)
DT[, new_value := value[which.max(age)], by = .(groups)]
基础 R
df$new_value <- ave(seq_len(nrow(df)), df$groups,
FUN = function(i) df$value[i][which.max(df$age[i])])
df
# groups age value new_value
# 1 1 12 1 3
# 2 1 23 2 3
# 3 1 34 3 3
# 4 2 13 4 6
# 5 2 24 5 6
# 6 2 35 6 6
# 7 3 13 7 9
# 8 3 25 8 9
# 9 3 36 9 9
基本的 R 方法似乎是最不优雅的解决方案。我相信 ave
是最好的方法,但它有很多限制,首先是它只适用于一个 value-object (value
)其他人(我们需要知道 age
)。