[英]How to compile multiple csv files into a single xlsx file using R?
Say I have many csv files in a directory called Path
:假设我在名为
Path
的目录中有许多 csv 文件:
abc.csv
def.csv
xyz.csv
How can I compile these files into a single xlsx file where each csv becomes its own tab?如何将这些文件编译成单个 xlsx 文件,其中每个 csv 都成为自己的选项卡? I've tried using the below function but unfortunately only the first csv ultimately appears in the xlsx:
我试过使用下面的 function 但不幸的是只有第一个 csv 最终出现在 xlsx 中:
path <- "Path"
filenames_list <- list.files(path = path, full.names = TRUE)
for (i in 1:length(filenames_list)) {
sheet_name <- strsplit(strsplit(filenames_list[i], "/")[[1]][4], "\\.")[[1]][1]
file_name <- paste0('Path/output.xlsx')
temp <- read.csv(filenames_list[i])
write.xlsx(temp, file = file_name, sheetName = sheet_name, row.names = F, append = T)
}
Any recommendations?有什么建议吗?
You can try this approach with sapply
-您可以使用
sapply
尝试这种方法 -
path <- "Path"
filenames_list <- list.files(path = path, full.names = TRUE)
list_files <- sapply(filenames_list, read.csv, simplify = FALSE)
names(list_files) <- tools::file_path_sans_ext(basename(names(list_files)))
writexl::write_xlsx(list_files, 'data.xlsx')
Here is a possible tidyverse
solution:这是一个可能的
tidyverse
解决方案:
library(openxlsx)
library(tidyverse)
# Make sure your working directory is set to the location where your .csv files are
list.files(pattern = "*.csv") %>%
map(., ~read_csv(.)) %>%
write.xlsx(., "My Multi-tabbed File.xlsx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.