Хотя другие решения работают нормально, я бы хотел упомянуть функцию top_n
в dplyr
, которая была создана для решения аналогичных задач:
library(dplyr)
my_df %>%
group_by(document) %>%
top_n(1, topic)
# A tibble: 2 x 3
# Groups: document [2]
# document topic gamma
# <int> <int> <dbl>
# 1 1 3 0.00993
# 2 2 3 0.133
Другое простое решение Base R также:
my_df <- my_df[order(my_df$topic, decreasing = TRUE), ]
my_df[!duplicated(my_df$document), ]
# document topic gamma
# 3 1 3 0.009929329
# 6 2 3 0.132816810
Данные
my_df <- structure(list(document = c(1L, 1L, 1L, 2L, 2L, 2L),
topic = c(1L, 2L, 3L, 1L, 2L, 3L),
gamma = c(0.932581726, 0.015250915, 0.009929329,
0.032864538, 0.012939786, 0.13281681)),
class = "data.frame", row.names = c(NA, -6L))