read all files in a directory into a data frame, with a column recording filename in r
main.r
# Set directory pathdir_path <- "/path/to/directory/"# Get list of files in directoryfile_list <- list.files(dir_path)
# Initialize an empty list to store data frames read from each filedf_list <- list()
# Loop through each file in the file listfor (file_name in file_list) {
# Read the file into a data frame file_df <- read.csv(paste0(dir_path, file_name))
# Add a new column with the file name file_df$filename <- file_name
# Append the data frame to the list df_list <- append(df_list, list(file_df))
}
# Combine all data frames into a single data frameall_files_df <- do.call(rbind, df_list)
# Print the resulting data frameprint(all_files_df)