How can I write a custom function inside lapply to add a new column filename and fill it with name of the file.
I can do it using loop, I wish to learn and use lapply
Below is a sample code -
I created two tibbles and exported them as csv files.
I read them using lapply
I wish to add a column (filename) in each table that has the name of the file (repeating in all rows). it requires replacing read_csv inside lapply with a custom function which can read each csv file and add the desired column
library(tidyverse)
# Create two tibbles
file_1 <- tibble(x = 1:10)
file_2 <- tibble(x = rep("a", 50))
# write tibbles as csv files in the working directory
write_csv(x = file_1, file = "file 1.csv")
write_csv(x = file_2, file = "file 2.csv")
# list of all the csv files in the working dirctory
csv_files <- list.files(pattern = "*.csv")
# read all the csv files
tbl <- lapply(csv_files, read_csv)