Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Created September 5, 2017 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-dray/9dd93f2b47218f4e25344e18e5e138fd to your computer and use it in GitHub Desktop.
Save matt-dray/9dd93f2b47218f4e25344e18e5e138fd to your computer and use it in GitHub Desktop.
Loop read multiple files and assign object name based on filename
library(tidyverse)
library(stringr)
# list files in directory (in the format "x_y_z.csv")
list_files <- list.files("file/path")
for (i in seq_along(1:length(list_files))) {
# read the data
data_import <- read_csv(paste0("file/path/"
, list_files[i])
, na = c("NA", "")
)
# create object name based on filename
dataframe_name <- tolower(
paste0("prefix_"
, str_match( # function to find a matching string
list_files[i]
, "l_(.*?)_v" # extract string between "x_" and "_z" in filename
)[, 2] # extract second element of the str_match() output
)
)
# give the temporary data_import object the dataframe_name
assign(dataframe_name, data_import)
# output the filename and object name in the console
print(list_files[i])
print(dataframe_name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment