简体   繁体   English

在 R 中创建迭代循环以读取文件夹中的所有 Excel 文件,执行相同的 function,并导出为新文件

[英]Creating an iterative loop in R to read in all Excel files in a folder, performing the same function, and exporting as a new file

My current problem is that I have written the following:我目前的问题是我写了以下内容:

list.of.packages <- c("xlsx","dplyr","tidyverse")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
lapply(list.of.packages, require, character.only=T)

setwd("C:/Users/Google Drive/Global MIS/Global profiles/profiles_as_data")

AEC_data <- read.xlsx("G-AEC-DATA.xlsx", sheetIndex = 1, as.data.frame = T, check.names = F)

rownames(AEC_data) = make.names(AEC_data$AEC, unique = T)
AEC_data <- tibble::rownames_to_column(AEC_data,"Variable")
AEC_data <- select(AEC_data, -2)

AEC_data_reshaped <- reshape(AEC_data,
                             direction = "long",
                             varying = list(names(AEC_data)[2:17]),
                             v.names = "Value",
                             idvar = "AEC",
                             timevar = "Year",
                             times = 2004:2019)

AEC_data_reshaped <- select(AEC_data_reshaped, -4)
AEC_data_reshaped$Company <- "AEC"

write.xlsx(AEC_data_reshaped, "C:/Users//Google Drive/Global MIS/Global profiles/profiles_as_data_long/G-AEC-DATA-LONG.xlsx", row.names = F, showNA = F)

This just reads in G-AEC-DATA.xlsx, manipulates it into long form and does some cleaning.这只是读入 G-AEC-DATA.xlsx,将其处理成长格式并进行一些清理。 It then outputs it into a new folder with a new name.然后它将其输出到具有新名称的新文件夹中。

My issue is that I have to do this for 30 xlsx files.我的问题是我必须为 30 个 xlsx 文件执行此操作。 I basically need to find and replace "AEC" and iterate again for "ABC", say.例如,我基本上需要找到并替换“AEC”并再次迭代“ABC”。

I'm guessing I need to set up a list such as:我猜我需要设置一个列表,例如:

fileNames <- c("AEC.xlsx","ABC.xlsx")

for example, then iterate through each file name.例如,然后遍历每个文件名。 All the original files are in exactly the same format, I just need to switch out the ISO3 code and iterate through each file,所有原始文件的格式完全相同,我只需要切换出 ISO3 代码并遍历每个文件,

Thanks.谢谢。

maybe you can do something like this:也许你可以做这样的事情:

my_xlsx_files <- dir(path=my_path)
for (file in my_xlsx_files){
   #do what you want here and save
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM