Arrays 在R中的循环代码块内创建全局变量

Arrays 在R中的循环代码块内创建全局变量,arrays,r,loops,Arrays,R,Loops,我是R新手,正在尝试访问循环外的数据 # List of 100 stock data a <-c ("one", "two", "three", "four",...) i = 1 while (i <= length(a)) { # make a list_element.csv to be accessed from local storage formated_path <-paste(a[i], ".csv") if (!file.exists(for

我是R新手,正在尝试访问循环外的数据

# List of 100 stock data
a <-c ("one", "two", "three", "four",...)
i = 1
while (i <= length(a)) {
  # make a list_element.csv to be accessed from local storage
  formated_path <-paste(a[i], ".csv")
    if (!file.exists(formated_path)) {
      output <- paste("Data for ", a[i], "Not found!")
      print(output)
    } else {
      print("found")     
      a[i] <- read.csv(formated_path, header = TRUE)

      # I have tried to change the name of the array to
      # correspond  to the element name but no luck as
      paste(a[i], "_stock") <-read.csv(formated_path, header = TRUE)
      return(a[i])
      i = i + 1
    }
  }

如果你真的想继续你的方法,你正在寻找的函数叫做
assign
。但是,我想鼓励您以不同的方式思考您的问题:

a <- c("one", "two", "three", "four")
fileNames <- paste0(a, ".csv")
csvList <- lapply(fileNames, read.csv)
str(csvList)

并在调用
lappy
时使用它。您可以在中找到详细的解释

看起来您正在尝试加载多个
.csv
文件?如果是这样的话,在R中有更简单的方法。这个答案是最简单的:
a <- c("one", "two", "three", "four")
fileNames <- paste0(a, ".csv")
csvList <- lapply(fileNames, read.csv)
str(csvList)
myReadCsv <- function(fileName) {
  if (file.exists(fileName){
    read.csv(fileName)
  } else {
    message("File does not exist and is ignored")
    NULL
  }
}