0

I load all .csv files from a given folder and store all the names in the filenames variable.

# Loading files
filenames <- gsub("\\.csv$", "", list.files(pattern = "\\.csv$"))

# Reading files
for(i in filenames)
  {
    assign(i, read.csv(paste(i, ".csv", sep = ""), sep = ","))
  }

Now I'd like to access any dataframe with name that is in filenames. How can I do that?

thesecond
  • 362
  • 2
  • 9
  • 2
    Does this answer your question? [How to call an object with the character variable of the same name](https://stackoverflow.com/questions/9083907/how-to-call-an-object-with-the-character-variable-of-the-same-name) You can use `get(i)` within the loop or just pass the specific string. – caldwellst Nov 23 '21 at 10:59

1 Answers1

2

I would not recommend using the function get() as this can have bad consequences. I'd suggest using a more structured approach by mean of a list containing all you csv files. I don't have any data here so I will build upon your code.

# Loading files
filenames <- gsub("\\.csv$", "", list.files(pattern = "\\.csv$"))

# create a list with NULL
file_list = vector("list", length(filenames))

# name each element according to filenames
names(file_list) = filenames

# Loop over the list
# Please note that the iterator "i" now loops over the elements
# and does not take the real values in filenames

for (i in seq_along(file_list)) {
  current_file = read.csv(paste0(i, ".csv"))
  file_list[[ i ]] = current_file
}

Now you can access each element either with the standard indexing ([[) or via the names with the $ operator.

UPDATE

For an example about why you should avoid get(), please refer to this SO post.

Francesco Grossetti
  • 1,555
  • 9
  • 17
  • And if you still *really* want each file as it's own dataframe object in the environment, you can always use `list2env(file_list)` later. Either way, this should be the approach to read, not using `assign()`. –  Nov 23 '21 at 13:36