[R] Extracting File Basename without Extension

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Fri Jan 9 14:22:19 CET 2009


Berwin A Turlach wrote:
> G'day Wacek,
>
>
>   
>>> Or, in case that the extension has more than three letters or
>>> "myfile" is a vector of names:
>>>
>>> R> myfile <- "path1/path2/myoutput.txt"
>>> R> sapply(strsplit(basename(myfile),"\\."), function(x)
>>> R> paste(x[1:(length(x)-1)], collapse="."))
>>> [1] "myoutput"
>>> R> myfile2 <- c(myfile, "path2/path3/myoutput.temp")
>>> R> sapply(strsplit(basename(myfile2),"\\."), function(x)
>>> R> paste(x[1:(length(x)-1)], collapse="."))
>>> [1] "myoutput" "myoutput"
>>> R> myfile3 <- c(myfile2, "path4/path5/my.out.put.xls")
>>> R> sapply(strsplit(basename(myfile3),"\\."), function(x)
>>> R> paste(x[1:(length(x)-1)], collapse="."))
>>> [1] "myoutput"   "myoutput"   "my.out.put"
>>>
>>>   
>>>       
>> or have sub do the job for you:
>>
>> filenames.ext = c("foo.bar", basename("foo/bar/hello.dolly"))
>> (filenames.noext = sub("[.][^.]*$", "", filenames.ext, perl=TRUE))
>>     
>
>   

g'afternoon berwin,

> Apparently also a possibility, I guess it can be made to work with the
> original example and my extensions.
>   

i guess it does work with the original example and your extensions.

> Though, it seems to require the knowledge of perl, or at least perl's
> regular expression. 
>   

oh my, sorry.  it' so bad to go an inch out of the cosy world of r. 
but, as gabor pointed, 'perl=TRUE' is inessential here, so you actually
need to know just (very basic) regular expressions, with no 'perl'
implied.  having learnt this simple regex syntax you can avoid the need
for looking up strsplit and paste in tfm, so i'd consider it worthwhile.

vQ




More information about the R-help mailing list