我正在努力寻找一个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解决方案最有帮助.谢谢你

推荐答案

  • 您可以使用ensyms()来捕获列名,然后在仅找到一个最大值时索引到它们.
  • 要获取示例输出,您需要使用rowwise %>% mutate,而不是group_by %>% summarize.
  • 测试多个最大值时,使用dplyr::near()而不是==来减轻浮点错误.
  • 下面还包括NA次处理.
library(dplyr)

column_with_max <- function(..., na.rm = FALSE) {
  nms <- as.character(ensyms(...))
  vals <- c(...)
  max_val <- max(vals, na.rm = na.rm)
  if (is.na(max_val)) return(NA_character_)
  max_idx <- which(near(vals, max_val))
  if (length(max_idx) > 1) return("tie")
  nms[[max_idx]]
}

data %>%
  rowwise() %>%
  mutate(max_column = column_with_max(value1, value2, value3)) %>%
  ungroup()

结果:

# A tibble: 6 × 5
  group value1 value2 value3 max_column
  <chr>  <dbl>  <dbl>  <dbl> <chr>     
1 A          0      1      1 tie       
2 A          0      1      0 value2    
3 B          1      1      2 value3    
4 B          0      1      0 value2    
5 C          1      1      1 tie       
6 C          1      1      1 tie   

R相关问答推荐

使用na.locf在长格式数据集中输入具有多个时间点的数据集

根据shiny 应用程序中的数字输入更改图标 colored颜色

如何使用R中的dhrr函数将李克特量表的因子列从长转换为宽?

在使用ggroove后,将图例合并在gplot中

如何在R中添加截止点到ROC曲线图?

将向量组合到一个数据集中,并相应地命名行

当月份额减go 当月份额

在rpart. plot或fancyRpartPlot中使用带有下标的希腊字母作为标签?

在ggplot2的框图中绘制所有级别的系数

将二进制数据库转换为频率表

如何使这些react 表对象相互独立?

将项粘贴到向量中,并将它们分组为x的倍数,用空格分隔

扩展R中包含列表的数据框

使用未知字符数(不受限制的最大长度)的Lookback有什么好的替代方案?

如何阻止围堵地理密度图?

按组和连续id计算日期差

长/纬点继续在堪萨斯-SF结束,整齐的人口普查

每行不同列上的行求和

Broom.Mixed::Augment不适用于Sample::分析

对一个数据帧中另一个数据帧中的值进行计数