What I am looking to do is loop through all Excel files in a directory and, where value in column 'Account.ID' is a match to my created 'IDList', changed column 'Type' value to 'REDACTED'. Dataframe then needs to be exported back to the original Excel file, saved, closed and on to the next file.
The below code works for obtaining the list of files within the directory, opening the first file and making the necessary amendment.
Can anyone help please with writing the data back to the original Excel file and ensuring the loop works through to completion so all files are amended?
#ID list contains thousands, simplified for ease of reading
IDList <- c("7c850aaa", "07311bbb",)
MYFILEPATH <- "\\\\dcf.network\\data\\\\R\\Test Folder"
# get a vector of all filenames
files <- list.files(
path=MYFILEPATH,
full.names = TRUE,
recursive = TRUE
)
for (i in 1:length(files)) {
data <- read.xlsx(files[i])
cols <- c("Type")
data[data$Account.ID %in% IDList, cols] <- "REDACTED"
}
xlsx::write.xlsx(data, files[i])as the loop's last instruction.