You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言(dplyr)中按列分组并选取另一列字符数最多的行

解决按ID选取text列字符数最多行的问题

你的代码出错的核心原因是:你把字符串类型的text列和数字类型的字符数最大值做了相等比较,两者类型不匹配,自然无法匹配到任何行。

正确解法1:直接在filter中比较字符数

通过str_length(text)获取每个文本的字符数,再和组内的最大字符数比较:

library(dplyr)

df <- data.frame(id=c(1,2,2,1,3),
                 text=c("new town","car is sold","address is changed","to be confirmed","call later")) 

df %>% 
  group_by(id) %>% 
  filter(str_length(text) == max(str_length(text)))

运行结果:

# A tibble: 3 x 2
# Groups:   id [3]
     id text               
  <dbl> <chr>              
1     1 to be confirmed    
2     2 address is changed
3     3 call later         

正确解法2:先新增字符数列再筛选(更直观)

如果需要临时查看字符数,可以先新增一列,再筛选:

df %>% 
  mutate(text_len = str_length(text)) %>% 
  group_by(id) %>% 
  filter(text_len == max(text_len)) %>% 
  select(-text_len)  # 可选:移除临时列

处理并列最大值的情况

如果同一个ID下有多个文本的字符数并列最大:

  • 保留所有并列行:用slice_max并设置n = Inf
df %>% 
  group_by(id) %>% 
  slice_max(n = Inf, order_by = str_length(text))
  • 只保留其中一行(比如第一行):设置n = 1
df %>% 
  group_by(id) %>% 
  slice_max(n = 1, order_by = str_length(text))

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 18:22:47