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

R语言:将指定Excel中2018-2019年数据行插入目标数据框对应位置

R语言实现Excel数据提取与定向插入

需求说明

已有固定格式数据集存储在dacnet_yield_update till 2019.xlsx,需从Kharif crops yield_18-19.xlsx中提取year_id为2018、2019的有效行(即目标数据中存在对应作物-地区组合的行),并将这些行插入到目标数据集中对应作物、地区的原有数据行之后。


实现步骤

1. 安装并加载依赖包

需要用到读/写Excel和数据处理的工具包:

# 安装缺失的包
if (!require(readxl)) install.packages("readxl")
if (!require(dplyr)) install.packages("dplyr")
if (!require(openxlsx)) install.packages("openxlsx")

library(readxl)
library(dplyr)
library(openxlsx)

2. 读取源数据与目标数据

# 读取已有数据集
target_df <- read_excel("dacnet_yield_update till 2019.xlsx")

# 读取待提取的数据集
source_df <- read_excel("Kharif crops yield_18-19.xlsx")

3. 筛选需要插入的目标行

只保留year_id为2018、2019,且在目标数据中存在对应作物-地区组合的行:

insert_rows <- source_df %>%
  filter(year_id %in% c(2018, 2019)) %>%
  # 匹配目标数据中的作物-地区组合,确保只插入有效行
  inner_join(
    target_df %>% select(crop, state_id, district_id),
    by = c("crop", "state_id", "district_id")
  )

4. 合并并排序实现插入效果

通过添加排序标记,让新数据紧跟对应原有数据行:

# 为原有数据添加排序标记(优先级1)
target_df <- target_df %>%
  group_by(crop, state_id, district_id) %>%
  mutate(sort_tag = 1) %>%
  ungroup()

# 为待插入数据添加排序标记(优先级2)
insert_rows <- insert_rows %>%
  group_by(crop, state_id, district_id) %>%
  mutate(sort_tag = 2) %>%
  ungroup()

# 合并后按分组+排序标记+年份排序,完成插入
final_df <- bind_rows(target_df, insert_rows) %>%
  arrange(crop, state_id, district_id, sort_tag, year_id) %>%
  select(-sort_tag)  # 移除临时标记列

5. 导出最终结果

# 将处理后的数据写入新Excel文件
write.xlsx(final_df, "updated_dacnet_yield_2019.xlsx", rowNames = FALSE)

注意事项

  • 若你的数据中state_name/district_name比ID更适合作为匹配标识,可将inner_join中的匹配字段替换为这些名称字段
  • 最终输出文件updated_dacnet_yield_2019.xlsx即为完成插入操作后的数据集

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:27:31