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

在R中基于id部分匹配提取另一数据框score至新列的方法

解决方案

首先注意:df中的score如果是数字类型,002会自动转为2,所以先把score转为字符型保留前导零:

library(tidyverse)

# 修正score类型,保留前导零
df <- df %>% mutate(score = str_pad(score, width = 3, pad = "0"))

方案一:合并为单个斜杠分隔的score列

用str_starts判断df的id是否以dt的id为前缀,分组汇总后和dt左连接:

dt_with_combined_score <- dt %>%
  left_join(
    df %>%
      mutate(prefix = str_extract(id, "^[^.]+")) %>% # 提取df$id的前缀(第一个.之前的部分)
      group_by(prefix) %>%
      summarise(combined_score = str_c(score, collapse = "/")),
    by = c("id" = "prefix")
  ) %>%
  replace_na(list(combined_score = "无匹配")) # 无匹配时可替换为指定文本,也可保留NA

# 查看结果
dt_with_combined_score

输出示例:

# A tibble: 3 × 3
  id    city  combined_score
  <chr> <chr> <chr>
1 AR01  AM    2587/002/885
2 QR01  Bis   3372/002
3 KVC   CHB   无匹配

方案二:拆分为多个score列

先把每个前缀对应的score整理成列表,再展开为多列,无匹配填充NA:

dt_with_separated_scores <- dt %>%
  left_join(
    df %>%
      mutate(prefix = str_extract(id, "^[^.]+")) %>%
      group_by(prefix) %>%
      summarise(scores = list(score)),
    by = c("id" = "prefix")
  ) %>%
  unnest_wider(scores, names_sep = "_") %>%
  replace_na(list(scores_1 = NA, scores_2 = NA, scores_3 = NA)) # 按需补充列数

# 查看结果
dt_with_separated_scores

输出示例:

# A tibble: 3 × 5
  id    city  scores_1 scores_2 scores_3
  <chr> <chr> <chr>    <chr>    <chr>
1 AR01  AM    2587     002      885
2 QR01  Bis   3372     002      NA
3 KVC   CHB   NA       NA       NA

为什么ifelse会报错?

ifelse是逐元素判断的工具,只能处理一对一的匹配逻辑,但这里每个dt的id可能对应多个df的score(一对多关系),用ifelse无法处理这种批量的分组汇总/展开操作,所以会出现维度不匹配或逻辑错误。

内容的提问来源于stack exchange,提问作者Alegría

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:45:31