How to Get Extension of a File in R

When you are uploading files, you do need to know the filename and its extension. We have seen the functions related to the filename, and filepath like basename() function removes all paths up to and including the last path separator. Let’s see how to get the extension of the file in R.

How to Get Extension of a File in R

To get the extension of a file in R, use the file_ext() method. The file_ext() is not a built-in R method. To use the file_ext() method, you need to import the tools library.

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, then we will get the extension of that file using the file_ext() method. In the output, we can see that it returns R, the file extension for the R programming file.

How to get filename without extension in R

To get the filename without extension in R, use the file_path_sans_ext() method. The file_path_sans_ext() method is not a built-in R method. You need to use the tools library. Then you can use the above 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 for this tutorial.

Leave a Comment