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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.