[英]R: read a csv file from multiple folders and write a xslx file keeping the sheet names
目錄的結構為:
data -> topic1 -> question1 -> sheetName.csv
-> question2 -> sheetName.csv
...
-> topic2 -> question1 -> sheetName.csv
-> question2 -> sheetName.csv
...
我想要為每個“主題”提供一個excel文件的輸出。 在每個文件中,都有與該主題內的sheetName.csv對應的工作表。 例如,一個名為:topic1.xlsx的excel文件,包含3張紙,與主題1中的3張sheetName.csv文件對應。
但是,我也想保持工作表名稱與原始.csv文件中的相同。 請注意,“ sheetName”是隨機的(即不遵循任何模式)。
這是到目前為止我嘗試過的代碼:
library(readxl)
library(writexl)
library(dplyr)
pathName <- "/data/"
topicName <- list.files(path = pathName)
for(i in 1:length(topicName)) {
topicPath <- paste(pathName, topicName[[i]], sep = "")
files_to_read = list.files(
path = topicPath,
pattern = '*.csv',
recursive = TRUE,
full.names = TRUE
)
data_lst <- list()
data_lst <- lapply(files_to_read, read.csv)
setwd(pathName)
write_xlsx(data_lst, path = paste(topicName[[i]], ".", "xlsx", sep = ""))
}
我得到的輸出是每個主題都有相應csv工作表的excel文件,但是工作表名稱為“工作表1,工作表2等...”。 有沒有辦法在寫入excel文件時保留工作表名稱?
好的,首先,我將以編程方式生成CSV文件,以反映您描述的目錄結構。 CSV將被命名為數字的隨機字符串。
dir.create('data')
topics <- c("topic1", "topic2")
questions <- c("question1", "question2")
for(i in 1:length(topics)){
dir.create(paste0('data/', topics[i]), showWarnings = F)
for(j in 1:length(questions)){
dir.create(paste0('data/', topics[i], "/", questions[j]), showWarnings = F)
for(k in 1:3){
set.seed(Sys.time())
Sys.sleep(1)
sheet <- as.character(round(runif(1, 1, 99999999)))
print(sheet)
file.name = paste0('data/', topics[i], "/", questions[j], "/", sheet, ".csv")
write.csv(data.frame(x = 1), file = file.name)
}
}
}
接下來,要回答您的問題,
為了將CSV工作表名稱寫為XLSX工作簿名稱,我創建了一個for循環,使用兩次對strsplit()
調用從文件名中獲取工作表名稱,然后調用xlsx::write.xlsx()
寫入文件。 我使用xlsx
包來編寫xlsx,因為它允許指定工作表名稱並使用附加標志寫入同一xlsx。
library(xlsx)
library(dplyr)
pathName <- "data/"
topicName <- list.files(path = pathName)
for(i in 1:length(topicName)) {
topicPath <- paste(pathName, topicName[[i]], sep = "")
files_to_read = list.files(
path = topicPath,
pattern = '*.csv',
recursive = TRUE,
full.names = TRUE
)
data_lst <- list()
for(k in 1:length(files_to_read)){
sheet_name <- strsplit(strsplit(files_to_read[k], "/")[[1]][4], "\\.")[[1]][1]
file_name <- paste0("data/", topicName[[i]], ".xlsx")
dat <- read.csv(files_to_read[k])
write.xlsx(dat, file=file_name, sheetName=sheet_name, row.names=F, append=T)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.