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

如何移除所有关联f值相同的Utterance分组?

问题描述

需求:移除所有Utterance对应的f值完全相同的行。

用户尝试的tidyverse代码(运行报错):

library(tidyverse)
df %>%
  separate_rows(f, convert = TRUE) %>%
  group_by(Utterance) %>%
  filter(if_all(f), ~. != lead(.))

原始数据:

df <- data.frame(
  Utterance = c("B B C", "A A A", "A B C"),
  f = c("2,2,3", "1,1,1", "1,2,3")
)

期望输出结果:

# A tibble: 6 × 2
  Utterance     f
  <chr>     <int>
1 B B C         2
2 B B C         2
3 B B C         3
4 A B C         1
5 A B C         2
6 A B C         3
解决方案

正确代码实现

library(tidyverse)

df %>%
  separate_rows(f, convert = TRUE) %>%
  group_by(Utterance) %>%
  filter(n_distinct(f) > 1) %>%
  ungroup()

代码说明

  • separate_rows(f, convert = TRUE):将逗号分隔的f值拆分为多行,并自动转换为整数类型。
  • group_by(Utterance):按Utterance分组,便于判断每组内的f值是否完全一致。
  • filter(n_distinct(f) > 1):通过n_distinct(f)统计组内f的不同取值数量,仅保留取值数量大于1的组(即f值不全相同的组)。
  • 原代码的问题:if_all用法错误,且用lead(.)逐行比较的逻辑无法正确过滤掉所有f值相同的组,还会误删组内的部分行。

运行结果

执行上述代码后,输出与期望一致:

# A tibble: 6 × 2
  Utterance     f
  <chr>     <int>
1 B B C         2
2 B B C         2
3 B B C         3
4 A B C         1
5 A B C         2
6 A B C         3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:05:10