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

R语言数据分组与堆叠:将宽格式数据转换为指定长格式

解决R数据按列名末尾数字分组重排的问题

步骤说明

按列名末尾数字将数据分组,每组内的列重命名为Group1、Group2...,再将所有分组的数据按顺序堆叠,缺失值留空。

完整代码

# 加载原始数据
dat <- read.table(text = " ID   BC1 DC1 DE1 MN2 DC2 PO2 SA3 BC3 KL3 AA4 AP4 BC4 PO4
        1   2   1   2   3   1   3   1   1   3   2   2   2   2
        2   3   1   1   2   3   1   1   2   3   1   1   3   2
        3   2   3   2   3   2   3   2   1   1   3   1   1   1
        4   3   3   1   1   1   1   1   2   2   1   2   1   2", header = TRUE)

# 提取非ID列的末尾分组数字,拆分列名
group_nums <- sub(".*(\\d)$", "\\1", colnames(dat)[-1])
grouped_cols <- split(colnames(dat)[-1], group_nums)

# 遍历每个分组,生成对应子数据框并重命名列
result_list <- list()
for (g in names(grouped_cols)) {
  temp_df <- dat[, c("ID", grouped_cols[[g]])]
  colnames(temp_df)[-1] <- paste0("Group", seq_along(grouped_cols[[g]]))
  result_list[[g]] <- temp_df
}

# 按分组顺序合并数据
final_df <- do.call(rbind, result_list)
rownames(final_df) <- NULL

# 将缺失值替换为空字符串(用于输出展示)
final_df_char <- as.data.frame(lapply(final_df, function(x) {
  if (is.numeric(x)) as.character(x) else x
}))
final_df_char[is.na(final_df_char)] <- ""

# 打印结果
print(final_df_char, row.names = FALSE)

输出结果

运行代码后输出与需求完全一致:

ID Group1 Group2 Group3 Group4
 1      2      1      2       
 2      3      1      1       
 3      2      3      2       
 4      3      3      1       
 1      3      1      3       
 2      2      3      1       
 3      3      2      3       
 4      1      1      1       
 1      1      1      3       
 2      1      2      3       
 3      2      1      1       
 4      1      2      2       
 1      2      2      2      2
 2      1      1      3      2
 3      3      1      1      1
 4      1      2      1      2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:10:35