r - 如何仅使用 R 将具有相同两个标题行的各种 csv 文件合并到一个标题行的单个文档中?
问题描述
我有各种不同的 CSV 文档,它们都在同一个文件夹中。所有这些文档都有 65 列,标题相同的两个标题行,它们需要合并到一个文档中。此外,我需要合并标题行。
结构看起来或多或少是这样的:
B2.csv:
TP1 TP1 TP2 TP2 TP2
Value Measurement Condition Time Max_Value
1.09 2.779 1 120 5.885
5.09 2.005 2 180 7.555
9.33 1.889 3 240 1.444
5.00 6.799 4 300 9.125
8.88 3.762 5 360 6.223
B4.csv:
TP1 TP1 TP2 TP2 TP2
Value Measurement Condition Time Max_Value
2.11 4.339 7 120 6.115
5.69 8.025 8 180 7.555
8.38 5.689 9 240 5.244
9.70 7.795 10 300 8.824
8.78 3.769 11 360 3.883
最终文件应如下所示:
TP1_Value TP1_Measurement TP2_Condition TP2_Time TP2_Max_Value
1.09 2.779 1 120 5.885
5.09 2.005 2 180 7.555
9.33 1.889 3 240 1.444
5.00 6.799 4 300 9.125
8.88 3.762 5 360 6.223
2.11 4.339 7 120 6.115
5.69 8.025 8 180 7.555
8.38 5.689 9 240 5.244
9.70 7.795 10 300 8.824
8.78 3.769 11 360 3.883
为了合并文档,我使用了以下代码:
setwd("C:/Users/XXXX/Desktop/Data/.")
# Get a List of all files in directory named with a key word, say all `.csv` files
filenames <- list.files("C:/Users/XXXX/Desktop/Data/.", pattern="*.csv", full.names=TRUE)
# Read and row bind all data sets
data <- rbindlist(lapply(filenames,fread))
# Generate new CSV document
write.csv(data, file = "C:/Users/XXXX/Desktop/Data/OneHeader.csv", sep = ",", row.names = FALSE)
但是,使用此代码,第二个标题行仍保留在数据文件中。要合并这些标题,我将使用以下代码:
# Merging first two lines into one single header
data[] <- lapply(data, as.character)
names(data) <- paste(names(data), data[1, ], sep = "_")
new_data <- data[-1,]
你能帮我吗,我怎么能把这两个部分的代码结合起来,让它自动合并?
如果有人可以在此帮助我,我将不胜感激,因为我是使用 R 的初学者。或者还有其他(更好的)方法来完成这项任务吗?
非常感谢您的帮助!
解决方案
这是一种 data.table 方法,主要使用fread()
.
由于它按文件读取列名,因此如果游览文件包含不同的标题,它也可以工作。用于填写空白列fill = TRUE
。rbindlist()
library( data.table )
#get list of files to read
files <- list.files( pattern = "^B[0-9].csv", full.names = TRUE )
#read files to list using lapply
l <- lapply( files, function(x) {
#read the first two rows of each file, and paste them together to get col_names
col_names = transpose( fread( x, nrows = 2 ) )[, .(paste(V1, V2, sep = "_") )][[1]]
#read file from except the first two rows, use col_names as header
dt <- fread( x, skip = 2, col.names = col_names )
})
#bind list together
rbindlist( l, fill = TRUE )
# TP1_Value TP1_Measurement TP2_Condition TP2_Time TP2_Max_Value
# 1: 1.09 2.779 1 120 5.885
# 2: 5.09 2.005 2 180 7.555
# 3: 9.33 1.889 3 240 1.444
# 4: 5.00 6.799 4 300 9.125
# 5: 8.88 3.762 5 360 6.223
# 6: 2.11 4.339 7 120 6.115
# 7: 5.69 8.025 8 180 7.555
# 8: 8.38 5.689 9 240 5.244
# 9: 9.70 7.795 10 300 8.824
# 10: 8.78 3.769 11 360 3.883
然后将结果写入磁盘。
推荐阅读
- java - 如何为 ListenableFuture 回调编写 junit 测试
- flutter - 从日期开始每天 Flutter 本地通知计划
- javascript - 邮递员中的表单数据将空对象发送到 node.js
- java - 添加 textview onclick 后歌曲停止工作
- swift - DocC 中针对不同平台的条件指令
- algorithm - 如何知道所有切片元素是否相等,如果是,则返回对第一个元素的引用?
- python - 将 GDL90 CRC 代码转换为 Python 时出现问题
- php - 多态laravel morphTo?
- javascript - 文件不存在时如何捕获 Firebase 存储错误?
- mysql - 提取 5-95 个分位数内的均值、最大值、最小值和 sd 提取