Here are two ways to get an extension of a file in R:
- Using the file_ext() method from the tools package
- Using regular expression
Method 1: Using the file_ext() from tools package
Install the tools package if you have not:
install.packages("tools")
Now, you can load the package like this:
library("tools")
After importing the “tools” package, now you can use the “file_ext()” function.
Visual representation
Before getting the extension of a file, you need to check if a file exists.
To check if the file exists, use the file.exists() method. If it exists, then you can go further and use the file_ext() function.
Example
library(tools)
file <- "dataframe.R"
if (file.exists(file)) {
file_ext(file)
} else {
cat("The file does not exist")
}
Output
[1] "R"
Method 2: Using regular expression
If you prefer not to use an external package or need more control, you can use regular expressions with the sub() or gsub() function.
Example
file <- "dataframe.R"
extension <- sub(".*\\.", "", file)
print(extension)
Output
[1] "R"
Get a filename without an extension
To get the filename without extension, use the “file_path_sans_ext()” method. Unfortunately, the file_path_sans_ext() method is not a built-in method.
Example
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 seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.