Assuming that the file name is consistent to <country> - GDP.xlsx
and <country> - GNP.xlsx
:
library(xlsx)
# Change following as needed
path <- "C:/OneXLSX/"
# Fetch only the files from the folder
files <- list.files(path, pattern = "*.xlsx")
# Get the countries name only
countries <- unique(unlist(strsplit(files, " -(.*)")))
# Loop through each country, read GDP/GNP and write them to one single file
for (each in countries){
GDP <- read.xlsx(paste(path, each, " - GDP.xlsx", sep = ""), 1, header = TRUE)
GNP <- read.xlsx(paste(path, each, " - GNP.xlsx", sep = ""), 1, header = TRUE)
write.xlsx(GDP, paste(path, each, ".xlsx", sep = ""),
sheetName = "GDP", row.names = FALSE)
write.xlsx(GNP, paste(path, each, ".xlsx", sep = ""),
sheetName = "GNP", append = TRUE, row.names = FALSE)
}
My package of choice to work with Excel files is xlsx. Please feel free to change it to your preferred package and update the syntax as needed.
I apologize if the code is not pretty.