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

如何在R中为按年份分块的Excel数据集添加年份列并整合数据

解决R中按年份分块数据集的整合问题

你手头的数据集按年份分块存储,每块以年份值开头,接着是表头行,然后是对应分组的数据。需要提取年份作为单独列,清理无关行并整合为标准格式,以下是两种高效实现方式:

方法一:使用Base R

# 将矩阵转为数据框(cbind默认生成矩阵)
df <- as.data.frame(df, stringsAsFactors = FALSE)

# 识别年份行:Group列为数字且Value为NA的行
year_rows <- which(!is.na(as.numeric(df$Group)) & is.na(df$Value))
years <- as.numeric(df$Group[year_rows])

# 为每行分配对应年份
df$Year <- NA
for (i in seq_along(year_rows)) {
  start <- year_rows[i]
  end <- ifelse(i == length(year_rows), nrow(df), year_rows[i+1]-1)
  df$Year[start:end] <- years[i]
}

# 过滤年份行和表头行,保留有效数据
clean_df <- df[!df$Group %in% c("Group", as.character(years)), ]
# 重置行名
rownames(clean_df) <- NULL
# 调整列顺序并转换Value类型
clean_df <- clean_df[, c("Year", "Group", "Value")]
clean_df$Value <- as.numeric(clean_df$Value)

print(clean_df)

方法二:使用tidyverse工具(dplyr + tidyr)

library(dplyr)
library(tidyr)

df <- as_tibble(df) %>%
  # 标记年份行并向下填充年份值
  mutate(Year = ifelse(!is.na(as.numeric(Group)) & is.na(Value), Group, NA)) %>%
  fill(Year, .direction = "down") %>%
  # 过滤无效行
  filter(Group != "Group", !is.na(as.numeric(Value))) %>%
  # 转换数据类型并调整列顺序
  mutate(Year = as.numeric(Year), Value = as.numeric(Value)) %>%
  select(Year, Group, Value)

print(df)

运行任意一种方法的代码,都能得到你需要的整合后数据集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:05:16