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

如何在R语言中将单行转换为列并处理带子列的数据框

解决方案:将数据框第二行转为新列

原始数据框结构

运行你提供的代码后,原始数据框的结构如下:

print(df)
#                  ID Metric 1 Metric 1 Metric 1 Metric 2 Metric 2 Metric 2 Metric 3 Metric 3 Metric 3
# 1 Reporting Month    202201    202202    202203    202201    202202    202203    202201    202202    202203
# 2           Type 1       30        5       44       13       70       29       65       27       10
# 3           Type 2       77       47       10       86        3       61       76       41       47
# 4           Type 3       73       91       68       26       92        8       70       73       72
# 5           Type 4       56       30       62       45        5       23       55       75       12

转换思路

我们需要把第一行的Reporting Month值与对应的Metric列关联,同时把第二到第五行的Type作为分类列,最终转成「ID - Metric - Reporting Month - Value」的长格式数据框。

方法一:使用tidyverse(推荐)

# 安装并加载tidyverse包(首次使用需安装)
# install.packages("tidyverse")
library(tidyverse)

# 1. 提取第一行的月份信息,与Metric列名配对
col_metadata <- tibble(
  metric = colnames(df)[-1],  # 排除第一列的ID
  reporting_month = as.character(unlist(df[1, -1]))  # 提取第一行的月份值并转为字符型
)

# 2. 转换数据为长格式,合并月份信息
final_df <- df[-1, ] %>%  # 去掉第一行的标题行
  pivot_longer(cols = -ID, names_to = "metric", values_to = "value") %>%  # 转成长格式
  left_join(col_metadata, by = "metric") %>%  # 关联月份信息
  select(ID, metric, reporting_month, value) %>%  # 调整列顺序
  mutate(value = as.numeric(value))  # 确保数值列类型正确

# 查看结果
head(final_df)

输出结果示例:

# A tibble: 6 × 4
  ID     metric   reporting_month value
  <chr>  <chr>    <chr>           <dbl>
1 Type 1 Metric 1 202201             30
2 Type 1 Metric 1 202202              5
3 Type 1 Metric 1 202203             44
4 Type 1 Metric 2 202201             13
5 Type 1 Metric 2 202202             70
6 Type 1 Metric 2 202203             29

方法二:使用Base R

如果不想加载额外包,可使用Base R实现:

# 提取月份和Metric信息
month_vals <- as.character(unlist(df[1, -1]))
metric_names <- colnames(df)[-1]

# 提取数据部分(去掉第一行和第一列)
data_vals <- as.matrix(df[-1, -1])
rownames(data_vals) <- df[-1, 1]

# 构建最终数据框
final_df_base <- data.frame(
  ID = rep(rownames(data_vals), each = length(metric_names)),
  metric = rep(metric_names, times = nrow(data_vals)),
  reporting_month = rep(month_vals, times = nrow(data_vals)),
  value = as.numeric(data_vals),
  stringsAsFactors = FALSE
)

# 查看结果
head(final_df_base)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:40:32