LeroxXx LeroxXx - 22 days ago 10
R Question

Loop to replace "x" in whole code with list of diffrentent replacements

I'm new to R and I'm little stuck right now.
So, I wrote a code that looks somehow like this (this is only the beginning):

# Load all EUR Files
setwd(EUR)
filenames <- list.files(path = EUR)
MSCIeur <- do.call("rbind", lapply(filenames, read.csv, header = TRUE, sep = ";"))


Now I need to run this code several times for diffrent currencies, so my question is: Is there a way to run the same code multiple times and the first time it runs it uses "EUR" the next time it replaces all "EUR" in the code with "USD" etc. or do I need to copy paste the whole code and just replace all "EUR" with "USD" manually?

Thx to anybody that took the time to read this :)

Answer

Try a for loop, you can set different working directories and store all your data inside a list:

curr.name <-  gsub(x = list.dirs('.', recursive=FALSE), pattern = "./", replacement ="")

curr <- paste(getwd(), curr.name, sep = "/")

___________________________________________________________________________________________

MSCI <- list()

for(i in 1:length(curr)){
  setwd(curr[i])
  filenames <- list.files(path = curr[i])
  MSCI[[i]] <- do.call("rbind", lapply(filenames, read.csv, header = TRUE, sep = ";"))
}

names(MSCI) <- curr.name

___________________________________________________________________________________________

# Other way

for(i in 1:length(curr)){
  setwd(curr[i])
  filenames <- list.files(path = curr[i])
  assign(curr.name[i],do.call("rbind", lapply(filenames, read.csv, header = TRUE, sep = ";")))
}
Comments