0

I am new to R and am trying to access data outside a loop

# 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
    }
  }

My desired outcome is to be able to use the individually loaded .csvs with other functions outside the loop. I do not desire a multidimensional array, just individual arrays corresponding to the array element as:

# Desired output
print(one)  # Should be the elements of a
Phil
  • 4,344
  • 2
  • 23
  • 33
  • 1
    It looks like you're trying to load multiple `.csv` files? If so, there are much easier ways to do this in R. This answer is one of the easiest: http://stackoverflow.com/a/40943207/3022126 – Phil May 21 '17 at 12:46

1 Answers1

0

If you really want to pursue your approach, the function you are looking for is called assign. However I would like to encourage you to think about your problem a bit differently:

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

Rather than the imperative approach from the question you can take advantage of Rs ability to work on vectors (paste) and functional programming (lapply).

If you need to further handle missing files, you can define a new read.csv function containing that logic:

myReadCsv <- function(fileName) {
  if (file.exists(fileName){
    read.csv(fileName)
  } else {
    message("File does not exist and is ignored")
    NULL
  }
}

And use it in the call to lapply. You can find detailed explanations in Advanced R.

Sebastian
  • 840
  • 6
  • 11