使用group by获取另一列的最大值对应的值

Vic*_*man 6 grouping r survey dplyr data.table

在我的数据集中,受访者被分组在一起,并且有关于他们年龄的可用数据。我希望同一组中的所有人都具有该组中最年长的人的价值。

所以我的示例数据如下所示。

      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
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样

> 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
Run Code Online (Sandbox Code Playgroud)

知道如何使用 dplyr 做到这一点吗?

我尝试过类似的方法,但它不起作用

df %>% 
        group_by(groups) %>% 
        mutate(new_value = df$value[which.max(df$age)])
Run Code Online (Sandbox Code Playgroud)

r2e*_*ans 10

首先,“从不”(好吧,几乎df$从不)在 dplyr 管道中使用。在这种情况下,每次df$value[which.max(df$age)]都引用原始数据,而不是分组数据。在该数据集中的每个组中,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
Run Code Online (Sandbox Code Playgroud)

数据表

library(data.table)
DT <- as.data.table(df)
DT[, new_value := value[which.max(age)], by = .(groups)]
Run Code Online (Sandbox Code Playgroud)

碱基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
Run Code Online (Sandbox Code Playgroud)

基本 R 方法似乎是看起来最不优雅的解决方案。我相信这ave是最好的方法,但它有很多限制,首先是它只适用于一个对象(value),而没有其他值(我们需要知道age)。