Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filename without extension in R

Tags:

r

r-faq

I have a file:

ABCD.csv  

The length before the .csv is not fixed and vary in any length.

How can I extract the portion before the .csv?

like image 717
Matrix.cursor Avatar asked Mar 18 '15 04:03

Matrix.cursor


People also ask

How to read file without extension in R?

If you have fixed-width data, use read. fwf() or readr::read_fwf() to import your data. Whether or not a file has a particular extension is irrelevant to R.

How to get extension of 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. Now, you can use the file_ext() method.

How do I know the file type in R?

Bookmark this question. Show activity on this post. In linux we can use file command to get the file type based on the content of the file (not extension).


2 Answers

There's a built in file_path_sans_ext from the standard install tools package that grabs the file without the extension.

tools::file_path_sans_ext("ABCD.csv") ## [1] "ABCD" 
like image 100
Tyler Rinker Avatar answered Sep 20 '22 13:09

Tyler Rinker


basename will also remove the path leading to the file. And with this regex, any extension will be removed.

filepath <- "d:/Some Dir/ABCD.csv" sub(pattern = "(.*)\\..*$", replacement = "\\1", basename(filepath))  # [1] "ABCD" 

Or, using file_path_sans_ext as Tyler Rinker suggested:

file_path_sans_ext(basename(filepath))  # [1] "ABCD" 
like image 23
Jason V Avatar answered Sep 21 '22 13:09

Jason V