To get the extension of a file in R, you can use the “file_ext()” method from the tools package.
library("tools")
Now, you can use the file_ext() method.
To check if the file exists in R, use the file.exists() method.
library(tools)
file <- "dataframe.R"
if (file.exists(file)) {
file_ext(file)
} else {
cat("The file does not exist")
}
Output
[1] "R"
You can see that first, we checked if the file exists, and if it does, we will get the extension of that file using the file_ext() method. Then, in the output, we can see that it returns R, the extension of the R programming file.
How to get a filename without extension in R
To get the filename without extension in R, use the “file_path_sans_ext()” method. Unfortunately, the file_path_sans_ext() method is not a built-in R method.
library(tools)
file <- "dataframe.R"
if (file.exists(file)) {
file_path_sans_ext(file)
} else {
cat("The file does not exist")
}
Output
[1] "dataframe"
You can also use the basename() function to remove the path leading to the file, and with this regex, any extension will be removed.
library(tools)
file <- "dataframe.R"
if (file.exists(file)) {
sub(pattern = "(.*)\\..*$", replacement = "\\1", basename(file))
} else {
cat("The file does not exist")
}
Output
[1] "dataframe"
That is it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.