[英]Read and merge multiple xlsx files with different structure in R
I would like to read and merge multiple (>20) .xlsx files using R.我想使用 R 读取和合并多个 (>20) .xlsx 文件。
This is how my .xlsx files look.这就是我的 .xlsx 文件的外观。
Sample X Y Z
Sample1 5 3 1
Sample2 4 1 11
Sample3 9 11 9
Sample A B Z
Sample4 12 1 1
Sample5 6 1.1 1.41
Sample6 7 91 1
Sample C A Z
Sample7 4 2 9
Sample8 98 11 61
I would like to merge them into a single df with the Headers "Sample", "X", "Y", "Z", "A", "B", "C".我想将它们合并为一个带有标题“示例”、“X”、“Y”、“Z”、“A”、“B”、“C”的 df。 In no particular order, but it should contain all.没有特定的顺序,但它应该包含所有内容。
I found a few solutions which work with .xlsx files with the same structure (eg Merge multiple Excel files starting at row in R ) but they won't work with my problem.我找到了一些解决方案,它们适用于具有相同结构的 .xlsx 文件(例如, 从 R 中的行开始合并多个 Excel 文件),但它们无法解决我的问题。
This could be easily achieved via dplyr::bind_rows
which in contrast to rbind
allows for binding df's by row with differing number of columns and column names:这可以通过dplyr::bind_rows
轻松实现,与rbind
相比,它允许按行绑定具有不同列数和列名的 df:
df1 <- read.table(text = "Sample X Y Z
Sample1 5 3 1
Sample2 4 1 11
Sample3 9 11 9", header = TRUE)
df2 <- read.table(text = "Sample A B Z
Sample4 12 1 1
Sample5 6 1.1 1.41
Sample6 7 91 1", header = TRUE)
df3 <- read.table(text = "Sample C A Z
Sample7 4 2 9
Sample8 98 11 61", header = TRUE)
df <- list(df1, df2, df3)
dplyr::bind_rows(df)
#> Sample X Y Z A B C
#> 1 Sample1 5 3 1.00 NA NA NA
#> 2 Sample2 4 1 11.00 NA NA NA
#> 3 Sample3 9 11 9.00 NA NA NA
#> 4 Sample4 NA NA 1.00 12 1.0 NA
#> 5 Sample5 NA NA 1.41 6 1.1 NA
#> 6 Sample6 NA NA 1.00 7 91.0 NA
#> 7 Sample7 NA NA 9.00 2 NA 4
#> 8 Sample8 NA NA 61.00 11 NA 98
Thanks to @RonakShah and @Wimpel, this works:感谢@RonakShah 和@Wimpel,这有效:
#path to files
path <- "C:/Users/your/path"
#list diles
filenames_list <- list.files(path= path, full.names=TRUE)
#Store files in a list
All <- lapply(filenames_list,function(filename){
read.xlsx(filename)
})
#merge the dfs
merged_df <- data.table::rbindlist(All, use.names = TRUE, fill = TRUE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.