read all files in a directory into a data frame, with a column recording filename in r

main.r
# Set directory path
dir_path <- "/path/to/directory/"

# Get list of files in directory
file_list <- list.files(dir_path)

# Initialize an empty list to store data frames read from each file
df_list <- list()

# Loop through each file in the file list
for (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 frame
all_files_df <- do.call(rbind, df_list)

# Print the resulting data frame
print(all_files_df)
682 chars
28 lines

gistlibby LogSnag