在我的数据集中,受访者被分组在一起,并且有关于他们年龄的数据。我希望同一组中的所有人都具有该组中最年长的人的值(value)。
所以我的示例数据如下所示。
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
数据表
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
)。
关于r - 使用group by获取另一列最大值对应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70170074/