[R] eliminating string from a char vector

Marc Schwartz marc_schwartz at comcast.net
Sun Jun 22 04:34:37 CEST 2008


on 06/21/2008 09:19 PM milton ruser wrote:
> Hi there,
> 
> I have a list of filenames like
> 
> a<-c("file1.dbf", "file32.dbf", "myfile_temp.dbf")
> 
> and I would like to remove the ".dbf" string from all records and obtain
> somethink like
> 
> file1
> file32
> myfile_temp
> 
> Thanks in advance,
> 
> miltinho
> brazil

As is usually the case with R, there are several approaches:

 > sub("\\.dbf", "", a)
[1] "file1"       "file32"      "myfile_temp"

 > sapply(strsplit(a, "\\."), "[", 1)
[1] "file1"       "file32"      "myfile_temp"

 > substr(a, 1, nchar(a) - 4)
[1] "file1"       "file32"      "myfile_temp"


My personal preference would be the first.

See ?sub, ?strsplit, ?sapply, ?substr and ?nchar for more information.

As an aside, if you should need to manipulate complete file paths to 
extract the file name, see ?basename

HTH,

Marc Schwartz



More information about the R-help mailing list