find the extension of a file in r

To find the extension of a file in R, we can use gsub function to extract the substring after the last dot (.) in the file name.

Here is an example function that takes a file path as input and returns the file extension:

main.r
get_extension <- function(file_path) {
  extension <- gsub(".*\\.", "", file_path)
  return(extension)
}

# example usage
file_path <- "/path/to/myfile.csv"
get_extension(file_path)  # returns "csv"
199 chars
9 lines

In this example, the gsub function removes all characters up to and including the last dot in the file name (.*\.), leaving only the extension. The returned extension does not include the dot. This should work for most file extensions, but some extensions may have multiple dots (e.g., ".tar.gz"), in which case this method will only return the characters after the last dot. In such cases, you may want to modify the function to extract the entire file extension.

gistlibby LogSnag