Home > Software design >  How do I extract name from path and add them as names of elements of list inside lapply
How do I extract name from path and add them as names of elements of list inside lapply

Time:03-22

How do I extract name from path and add them as names of elements of list inside lapply.

I want the name of the elements in the tbl_list to be [["Employees"]] and [["Performances"]] i.e. extract name of the csv_files after last _ till before .csv.

library(tidyverse)

# list of path of files
csv_files <- c("C:/Dropbox (UFL)/Projects/Datasets/Company_A_-_Employees.csv",
               "C:/Dropbox (UFL)/Projects/Datasets/Company_A_-_Performances.csv")


# read all files using lapply
tbl_list <- lapply(X = csv_files, FUN = read_csv)


tbl_list has two elements [[1]] and [[2]] corresponding to each csv_files.

CodePudding user response:

names(tbl_list) <- gsub(".*_(.*)\\.csv$", "\\1", csv_files)
  • Related