0

In R, I currently have a vector of characters such as:

character.vec
> "File1.mat"      "File2.mat"       "File3.mat"        "File4.mat" 

I was wondering if there were any functions to call on character.vec so that I can get something like:

"File1"      "File2"       "File3"        "File4" 

instead. Thanks!

user321627
  • 2,350
  • 4
  • 20
  • 43
  • 1
    It appears that you just want to strip off the file extensions, but I suspect your logic is something else. What is your logic? – Tim Biegeleisen Mar 28 '18 at 01:39

2 Answers2

4

I think you're after:

> sub("\\.mat", "", character.vec)
[1] "File1" "File2" "File3" "File4"

You need the \\ before the . to distinguish it from its use in regular expressions as matching any character (https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/regex).

More generally, if you wanted to replace everything in a string from the last period to the end, you could use:

sub("\\.[^\\.]*?$", "", character.vec)
James
  • 56
  • 2
2

There's also a built in way for parsing filenames without extensions:

> library(tools) # in base R, shouldn't need to load
> test <- c("File1.mat","File2.mat","File3.mat","File4.mat") 
> tools::file_path_sans_ext(test)
[1] "File1" "File2" "File3" "File4"
mysteRious
  • 4,102
  • 2
  • 16
  • 36