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

R语言:将DataFrame中同名列的值合并至对应单列

解决方案

你的数据本质是一个包含重复列名的扁平列表,每8个连续元素对应一行标准数据。可以通过以下步骤转换为标准8列DataFrame:

  1. 将扁平列表转换为一维向量
  2. 按每8个元素一组拆分,重组为矩阵
  3. 转换为DataFrame并指定正确列名

完整R代码

# 你的原始数据
messy_data <- structure(list(estimate1 = 0.714007764032839, estimate2 = 0.73845425164382, 
    statistic = -1.40159874057185, value = 0.161035103302344, 
    low = -0.0586319030790906, high = 0.00973892785712839, method = "DeLong's test for two correlated ROC curves", 
    alternative = "two.sided", estimate1 = 0.714007764032839, 
    estimate2 = 0.800820052750845, statistic = -6.74113868776472, 
    value = 1.57150111460365e-11, low = -0.112052677201869, high = -0.0615719002341422, 
    method = "DeLong's test for two correlated ROC curves", alternative = "two.sided", 
    estimate1 = 0.73845425164382, estimate2 = 0.800820052750845, 
    statistic = -8.74919112196137, value = 2.14887453642886e-18, 
    low = -0.0763367753757128, high = -0.0483948268383366, method = "DeLong's test for two correlated ROC curves", 
    alternative = "two.sided", estimate1 = 0.714007764032839, 
    estimate2 = 0.798989561276422, statistic = -5.95819444516776, 
    value = 2.55039957819806e-09, low = -0.112936786539709, high = -0.0570268079474558, 
    method = "DeLong's test for two correlated ROC curves", alternative = "two.sided", 
    estimate1 = 0.73845425164382, estimate2 = 0.798989561276422, 
    statistic = -8.28057748735473, value = 1.22579375899045e-16, 
    low = -0.0748636613513149, high = -0.046206957913888, method = "DeLong's test for two correlated ROC curves"))

# 转换步骤
values_vec <- unlist(messy_data)
col_names <- c("estimate1", "estimate2", "statistic", "value", "low", "high", "method", "alternative")

# 校验数据完整性:元素总数必须是8的倍数
if (length(values_vec) %% length(col_names) != 0) {
  stop("原始数据元素总数不是8的倍数,请检查是否缺失数据")
}

clean_df <- as.data.frame(matrix(values_vec, ncol = length(col_names), byrow = TRUE))
colnames(clean_df) <- col_names

# 查看转换结果
print(clean_df)

关键逻辑说明

  • unlist():将嵌套的扁平列表转为一维向量,严格保留原始数据的顺序
  • matrix(..., byrow=TRUE):按行拆分向量,每8个元素自动组成一行
  • colnames():为转换后的DataFrame指定标准列名,完成格式统一

内容的提问来源于stack exchange,提问作者R. E.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 14:15:37