Select 行基于列的非定向组合

Select rows based on non-directed combinations of columns

我正在尝试 select 根据前两列中的值的组合,select 数据框的第三列中的最大值。

我的问题与 类似,但我找不到实现所需内容的方法。

编辑:示例数据已更改,使列名更加明显。

这是一些示例数据:

library(tidyr)
set.seed(1234)
df <- data.frame(group1 = letters[1:4], group2 = letters[1:4])
df <- df %>% expand(group1, group2)
df <- subset(df, subset = group1!=group2)
df$score <- runif(n = 12,min = 0,max = 1)
df

    # A tibble: 12 × 3
   group1 group2       score
   <fctr> <fctr>       <dbl>
1       a      b 0.113703411
2       a      c 0.622299405
3       a      d 0.609274733
4       b      a 0.623379442
5       b      c 0.860915384
6       b      d 0.640310605
7       c      a 0.009495756
8       c      b 0.232550506
9       c      d 0.666083758
10      d      a 0.514251141
11      d      b 0.693591292
12      d      c 0.544974836

在此示例中,第 1 行和第 4 行是 'duplicates'。我想 select 第 4 行,因为分数列中的值大于第 1 行中的值。最终我希望返回一个数据框,其中包含 group1 和 group2 列以及分数列中的最大值。所以在这个例子中,我希望返回 6 行。

我如何在 R 中执行此操作?

我更愿意分两步处理这个问题:

library(dplyr)

# Create function for computing group IDs from data frame of groups (per column)
get_group_id <- function(groups) {
  apply(groups, 1, function(row) {
    paste0(sort(row), collapse = "_")
  })
}
group_id <- get_group_id(select(df, -score))

# Perform the computation
df %>%
  mutate(groupId = group_id) %>%
  group_by(groupId) %>%
  slice(which.max(score)) %>%
  ungroup() %>%
  select(-groupId)