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

R语言中匹配两数据集ID并按State分组统计

问题描述

以下代码创建两个数据集:

df1 <- 
  read.table(textConnection("ID   Code   Date1 Date2
1 I611 01/01/2021 03/01/2021
2 L111 04/01/2021 09/01/2021
3 L111 01/01/2021 03/01/2021
4 Z538 08/01/2021 11/01/2021
5 I613 08/08/2021 09/09/2021
"), header=TRUE)

df2 <- 
  read.table(textConnection("ID   State   
  1 Washington
  49 California
  1 Washington
  40 Texas
  1 Texas
  2 Texas
  2 Washington
  50 Minnesota
  60 Washington"), header=TRUE)

需求:在df2中筛选出ID存在于df1$ID中的记录,按State分组统计每个州的对应记录数,期望输出:

StateIDs
Washington3
Texas2

解决方案

方法一:基础R实现

无需额外安装包,用原生R函数即可完成:

# 筛选df2中ID出现在df1里的记录
filtered_data <- df2[df2$ID %in% df1$ID, ]

# 按State分组计数
count_table <- table(filtered_data$State)

# 转换为目标格式的数据框
final_result <- as.data.frame(count_table)
colnames(final_result) <- c("State", "IDs")

print(final_result)

输出结果:

State IDs
Washington   3
      Texas   2

方法二:tidyverse(dplyr)实现

如果日常使用tidyverse工具链,代码更简洁易读:

library(dplyr)

final_result <- df2 %>%
  filter(ID %in% df1$ID) %>%  # 保留ID在df1中存在的行
  group_by(State) %>%         # 按州分组
  summarise(IDs = n())        # 统计每组行数

print(final_result)

输出结果:

# A tibble: 2 × 2
  State       IDs
  <chr>     <int>
1 Texas         2
2 Washington    3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:50:24