首页 > 解决方案 > 如何在 R 中动态组合具有不同列名的数据框?

问题描述

我有一个分析脚本,可以处理具有相似结构但列名不同的批次数据。我需要为以后的 ETL 脚本保留列名,但我们想做一些处理,例如:

results <- data.frame();
for (name in names(data[[1]])) {   
    # Start by combining each column into a single matrix
    working <- lapply(data, function(item)item[[name]]);
    working <- matrix(unlist(working), ncol = 50, byrow = TRUE);

    # Dump the data for the archive
    write.csv(working, file = paste(PATH, prefix, name, '.csv', sep = ''), row.names = FALSE);

    # Calculate the mean and SD for each year, bind to the results
    df <- data.frame(colMeans(working), colSds(working));
    names(df) <- c(paste(name, '.mean', sep = ''), paste(name, '.sd', sep = ''));

    # Combine the working df with the processing one
}

根据示例中的最后一条评论,如何组合数据框?我已经尝试过rbindrbind.fill但都没有工作,它们可能是数据文件中的 10 到 100 个不同的列名。

标签: r

解决方案


这可能是搜索正确关键字的更多问题,但该cbind方法实际上是与矩阵一起使用的方法,

# Allocate for the number of rows needed
results <- matrix(nrow = rows)

for (name in names(data[[1]])) {   
    # Data processing

    # Append the results to the working data
    results <- cbind(results, df)   
}

# Drop the first placeholder column created upon allocation
results <- results[, -1];

显然,问题是列需要具有相同的行数,否则只需将列附加到矩阵即可。


推荐阅读