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

R语言匹配数据框字段字符串后复制行并填充目标字段的实现方法

R语言实现地点关键词匹配并生成新行

实现思路

无需拆分residual字段,直接对每行文本做全关键词匹配,将命中的编码拆分为独立行即可,无需依赖固定分隔符。

tidyverse 实现方案

先加载依赖包:

library(tidyverse)

核心代码:

result <- df %>%
  rowwise() %>%
  # 匹配所有命中的关键词对应编码
  mutate(matched = list(keys$codes[str_detect(residual, fixed(keys$key))])) %>%
  ungroup() %>%
  # 匹配结果拆分为独立行,无匹配结果也保留原行
  unnest_longer(matched, keep_empty = TRUE) %>%
  # 替换country字段:有匹配编码用编码,无匹配保留原值
  mutate(country = coalesce(matched, country)) %>%
  select(-matched)

运行上述代码得到的结果与你给出的预期输出完全一致。

基础R实现方案

如果你不想引入额外依赖,可以用基础R代码实现:

result <- do.call(rbind, lapply(1:nrow(df), function(i) {
  current_row <- df[i, ]
  hit_codes <- keys$codes[grepl(keys$key, current_row$residual, fixed = TRUE)]
  if (length(hit_codes) == 0) return(current_row)
  # 原行 + 匹配到编码的新行合并
  rbind(current_row, transform(current_row[rep(1, length(hit_codes)), ], country = hit_codes))
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:36:03