我正在努力寻找一个max()类型的函数,它不会返回"first '、"last"或随机,而且看起来很有希望的.max.simple()在CRAN上不再可用.
尽管多次try ,Chat GPT仍难以正确返回该内容,因此有人能帮忙吗?
library(dplyr)
# Function to find column name(s) with max value, handling tie
column_with_max <- function(...) {
values <- c(...)
max_value <- max(values)
max_indices <- which(values == max_value)
if (length(max_indices) > 1) {
return(paste(names(values)[max_indices], collapse = ", "))
} else {
return(names(values)[values == max_value])
}
}
# Sample data
data <- data.frame(group = c("A", "A", "B", "B", "C", "C"),
value1 = c(0, 0, 1, 0, 1, 1),
value2 = c(1, 1, 1, 1, 1, 1),
value3 = c(1, 0, 2, 0, 1, 1))
# Grouped column with max value and tie handling
result <- data %>%
group_by(group) %>%
summarise(max_column = column_with_max(value1, value2, value3))
期望的结果是:
output <- data.frame(group = c("A", "A", "B", "B", "C", "C"),
value1 = c(0, 0, 1, 0, 1, 1),
value2 = c(1, 1, 1, 1, 1, 1),
value3 = c(1, 0, 2, 0, 1, 1),
max_column = c("tie", "value2", "value3", "value2", "tie", "tie"))
我有多个分组变量和更大的数据,因此dspirr解决方案最有帮助.谢谢你