[R] Extracting File Basename without Extension

Rau, Roland Rau at demogr.mpg.de
Fri Jan 9 16:23:37 CET 2009


Hi, 

> [mailto:r-help-bounces at r-project.org] On Behalf Of Henrique 
> Dallazuanna
> 
> Try this also:
> 
> substr(basename(myfile), 1, nchar(basename(myfile)) - 4)
> 

This, of course, assumes that the extensions are always 3 characters.
Sometimes there might be more ("index.html"), sometimes less
("shellscript.sh").

Although my solution is not as compact as the others (I wish I was
proficient in 'mastering regular expressions'), I'd like to provide my
little code-snippet which does not require any regular expressions (but
expects a . in the filename).

######################
x1 <- "roland.txt"
x2 <- "roland.html"
x3 <- "roland.sh"

no.extension <- function(astring) {
  if (substr(astring, nchar(astring), nchar(astring))==".") {
    return(substr(astring, 1, nchar(astring)-1))
  } else {
    no.extension(substr(astring, 1, nchar(astring)-1))
  }
}

no.extension(x1)
no.extension(x2)
no.extension(x3)
######################

Hope this helps a bit,
Roland

P.S. Any suggestions how to become more proficient with regular
expressions? The O'Reilly book ("Mastering...")? Whenever I tried
anything more complicated than basic usage (things like ^ $ * . ) in R,
I was way faster to write a new function (like above) instead of finding
a regex solution.

By the way: it might be still possible to *write* regular expressions,
but what about code re-use? Are there people who can easily *read*
complicated regular expressions?

----------
This mail has been sent through the MPI for Demographic Research.  Should you receive a mail that is apparently from a MPI user without this text displayed, then the address has most likely been faked. If you are uncertain about the validity of this message, please check the mail header or ask your system administrator for assistance.




More information about the R-help mailing list