循环替换" x"在整个代码中包含不同替换的列表

时间:2016-11-10 16:17:43

标签: r loops

我是R的新手,而我现在很少被卡住了。 所以,我写的代码看起来像这样(这只是开头):

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

现在我需要针对不同的货币多次运行此代码,所以我的问题是:有没有办法多次运行相同的代码,第一次运行时使用&#34; EUR&#34;下次它取代所有&#34; EUR&#34;在&#34; USD&#34;的代码中等我是否需要复制粘贴整个代码,只需替换所有&#34; EUR&#34;用&#34; USD&#34;手动?

对任何花时间阅读此内容的人来说:)

1 个答案:

答案 0 :(得分:0)

尝试for循环,您可以设置不同的工作目录并将所有数据存储在列表中:

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 = ";")))
}