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

如何使用expand_grid复制数据框行并扩展state值?

问题与解决方案

问题背景

现有两个R数据框:

  • 职业数据框first,代码定义如下:
state <- c("00","00","32","32")
codetype <- c("19","19","19","19")
code <- c ("123456","123457","123456","123457")
codetitle <- c("doctors","lawyers","doctors","lawyers")

first <- data.frame(state,codetype,code,codetitle)
  • 数据框second,代码定义如下:
state <- c("01","01","04","04","05","05")
codetype <- c("19","19","19","19","19","19")
code <- c("123456","123457","123456","123457","123456","123457")
pct10 <- c(12.30,12.65,14.50,14.23,15.65,25.22)

second <- data.frame(state,codetype,code,pct10)

需求:从second中提取唯一的state值,生成与first原有行结构一致的新行,添加到first中,最终得到包含原数据和新增行的结果,要求使用expand_grid函数实现。

实现步骤

核心思路是先提取职业信息的唯一模板,再提取需要新增的州列表,通过expand_grid生成两者的笛卡尔积,最后合并到原数据中:

# 1. 提取first中除state外的唯一职业信息模板
职业模板 <- unique(first[, c("codetype", "code", "codetitle")])

# 2. 提取second中的唯一state值
新增州 <- unique(second$state)

# 3. 用expand_grid生成新行:每个州对应所有职业模板
新行数据 <- expand_grid(state = 新增州, 职业模板)

# 4. 合并原数据与新行数据
最终结果 <- rbind(first, 新行数据)

# 可选:调整行顺序以匹配示例结果(按state降序排列)
最终结果 <- 最终结果[order(最终结果$state, decreasing = TRUE), ]
# 重置行名
rownames(最终结果) <- NULL

最终结果

运行上述代码后,得到的最终结果如下:

> 最终结果
   state codetype   code codetitle
1    32       19 123456    doctors
2    32       19 123457    lawyers
3    05       19 123456    doctors
4    05       19 123457    lawyers
5    04       19 123456    doctors
6    04       19 123457    lawyers
7    01       19 123456    doctors
8    01       19 123457    lawyers
9    00       19 123456    doctors
10   00       19 123457    lawyers

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:20:54