0

When I run this code I get an error and I'm unsure what it means and what I am doing wrong.

filenames <- list.files(path = "C:/_path_to_files_folder", full.names=TRUE, recursive = TRUE, pattern='.csv')

cars <- NULL
for(i in seq_along(filenames)) {date[[i]] <- str_extract(filenames[[i]], "20[0-9][0-9]-[0-9][0-9]")
data <- read_csv(filenames[[i]], skip = 13, col_types = cols(.default = "c"))
data <- mutate(data, Month = date[[i]])
cars <- bind_rows(cars, data)}

Error in date[[i]] <- str_extract(filenames[[i]], "20[0-9][0-9]-[0-9][0-9]") : object of type 'closure' is not subsettable

PKumar
  • 10,106
  • 5
  • 32
  • 47
  • Two things I see: (1) you use both `date` and `data`, it seems they should be the same; (2) I don't see you create `data`, which means it is likely the base function `data(.)`, one of the risks of using variables named the same as functions. (The reason for your error is that `date` is *also* a function in base R ...) – r2evans Apr 06 '21 at 16:14
  • A *very* similar question earlier today: https://stackoverflow.com/q/66971684/3358272, there are answers there that are likely useful (just changing the regex to extract the `Month` portion of the filename). – r2evans Apr 06 '21 at 16:15
  • @r2evans thank you. How would I do what you mention in the second point? I've looked at the similar question but I want to keep the loop and these functions. –  Apr 07 '21 at 09:14
  • Using a loop here is actually not a good idea in general. While it will work, iteratively `rbind`-ing (using `bind_rows` here) frames together scales poorly. It is generally much better to use a `list` structure to store the intermediate frames and then bind them all at once. See https://stackoverflow.com/a/24376207/3358227 for some discussion on list-of-frames, even if you do not intend to keep it as a list. Regardless, use your `str_extract` code in place of the `strcapture` (into `monthnames` there). – r2evans Apr 07 '21 at 11:26

0 Answers0