Created
September 5, 2017 14:16
-
-
Save matt-dray/9dd93f2b47218f4e25344e18e5e138fd to your computer and use it in GitHub Desktop.
Loop read multiple files and assign object name based on filename
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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