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

R语言如何限制pivot_wider仅对匹配指定模式的行执行宽表转换

解决方法

你之前报错的原因是pivot_wider的names_from、values_from参数仅支持传入数据框的列名,不支持直接在参数内对列做子集筛选操作。
正确实现思路是先新增辅助列定义宽表转换的列名规则,再执行宽表转换,代码如下:

library(tidyverse)

# 测试数据
df <- data.frame(utterance = c("A and stuff", 
                               "X and something", 
                               "A and some more", 
                               "B etc.", 
                               "B", 
                               "x yz and so on", 
                               "BBB"),
                 timestamp = c("00:05:31.736 - 00:05:35.263", "00:05:31.829 - 00:05:36.449", 
                               "00:05:31.829 - 00:05:36.449", "00:05:31.829 - 00:05:36.449", 
                               "00:05:31.842 - 00:05:35.302", "00:05:35.088 - 00:05:36.134", 
                               "00:05:35.263 - 00:05:53.052"))

# 转换代码
df %>%
  mutate(
    # 定义宽表的列名:首字母为A/B则取首字母,其余统一归类到utterance列
    col_name = ifelse(grepl("^[AB]", utterance), str_sub(utterance, 1, 1), "utterance")
  ) %>%
  group_by(timestamp, col_name) %>%
  summarise(val = utterance, .groups = "drop") %>%
  pivot_wider(
    names_from = col_name,
    values_from = val
  )

运行后输出结果和预期完全一致:

# A tibble: 5 × 4
  timestamp                   A               utterance       B      
  <chr>                       <chr>           <chr>           <chr>  
1 00:05:31.736 - 00:05:35.263 A and stuff     NA              NA     
2 00:05:31.829 - 00:05:36.449 A and some more X and something B etc. 
3 00:05:31.842 - 00:05:35.302 NA              NA              B      
4 00:05:35.088 - 00:05:36.134 NA              x yz and so on  NA     
5 00:05:35.263 - 00:05:53.052 NA              NA              BBB  

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:36:04