find the name of a file in r

To find the name of a file in R, you can use the basename() function from the base package. This function takes a file path as an argument and returns the file name and extension.

main.r
path <- "/User/MyFolder/MyFile.csv"
file_name <- basename(path)
print(file_name) # MyFile.csv
94 chars
4 lines

If you have a set of file paths that you want to extract the file names from, you can use a combination of lapply() and basename() to apply the function to all paths in a vector or list.

main.r
paths <- c("/User/MyFolder/MyFile.csv", "/User/MyFolder/AnotherFile.txt")
file_names <- lapply(paths, basename)
print(file_names) # "MyFile.csv" "AnotherFile.txt"
163 chars
4 lines

If the file names contain additional information that you want to extract, you can use regular expressions with the gsub() function to remove unwanted characters.

main.r
file_names <- c("MyFile1_2021_08.csv", "MyFile2_2021_09.csv")
file_names_clean <- gsub("_\\d{4}_\\d{2}", "", file_names)
print(file_names_clean) # "MyFile1.csv" "MyFile2.csv"
175 chars
4 lines

gistlibby LogSnag