-1

Is there a way to loop this?

jan2018 <- read.csv(file = 'Jan2018.csv')
feb2018 <- read.csv(file = 'Feb2018.csv')
mar2018 <- read.csv(file = 'Mar2018.csv')
apr2018 <- read.csv(file = 'Apr2018.csv')
may2018 <- read.csv(file = 'May2018.csv')
jun2018 <- read.csv(file = 'Jun2018.csv')
jul2018 <- read.csv(file = 'Jul2018.csv')
aug2018 <- read.csv(file = 'Aug2018.csv')
sep2018 <- read.csv(file = 'Sep2018.csv')

How would the code look like?

ANSWER:

Here is a good example of how you would automatically import multiple files at once:

list_of_files <- list.files(pattern = "^starting_text")

data <- list_of_files %>%
  setNames(nm = c("jan", "feb", "mar", "apr", "may", "jun", "jul")) %>%
  map_df(read_xlsx, .id = "month")
koras
  • 15
  • 5
  • Possible duplicate of [Which is the best method to apply a script repetitively to n .csv files in R?](https://stackoverflow.com/questions/5799096/which-is-the-best-method-to-apply-a-script-repetitively-to-n-csv-files-in-r) – Parfait Mar 08 '19 at 18:14
  • Possible duplicate of [How to import multiple .csv files at once?](https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once) – divibisan Mar 08 '19 at 18:19

1 Answers1

1

Try this out:

file_names <- list.files(pattern = ".*2018.csv")
dates <- tolower(sub(".csv", "", file_names))

myList <- lapply(file_names, read.csv)


for (i in 1:length(myList)) {

  assign(paste0(dates[i]), as.data.frame(myList[[i]]))

}
J.Moon
  • 120
  • 1
  • 7
  • `list_of_files <- list.files(pattern = "^starting_text") data <- list_of_files %>% setNames(nm = c("jan", "feb", "mar", "apr", "may", "jun", "jul")) %>% map_df(read_xlsx, .id = "month")` – koras Apr 24 '19 at 16:38