r - 如何在 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
}
根据示例中的最后一条评论,如何组合数据框?我已经尝试过rbind
,rbind.fill
但都没有工作,它们可能是数据文件中的 10 到 100 个不同的列名。
解决方案
这可能是搜索正确关键字的更多问题,但该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];
显然,问题是列需要具有相同的行数,否则只需将列附加到矩阵即可。
推荐阅读
- r - Facet wrap 和填充点图
- amazon-web-services - 如何使用 TerraForm 创建部署 lambda 函数的管道
- c# - 使用自定义命名策略生成 Swagger 定义的问题
- python - 合并“左”,但在可能的情况下覆盖“右”值
- python - Keras:许多批量大小失败
- javascript - JavaScript - 遍历图像目录数组并将它们应用于图像
- jenkins - 确定 Jenkins 工作是如何开始的
- perl - 如何让 Dist::zilla 在 YAML 中指定最小 Perl 版本?
- java - 有没有办法很好地使用 gson 来获取一个包含在 java 中具有 4 个变量的数组的列表
- scrapy - Python Scrapy Splash 不渲染网站,卡在加载屏幕上