Re: [R] search path question

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Wed, 30 May 2007 12:32:11 +0100 (BST)

I meant essentially the same thing but returning file(fixed_up_name). You can vectorize this BTW:

search_file <- function(name, path=getOption("scanpath")) {

     fp <- c(name, file.path(path, name)) # better to use direct name first
     fp <- fp[file.exists(fp)]
     if(length(fp)) file(fp[1]) else stop(name, " not found")
}

Shortly things like

> read.table(search_file("passwd"))

will close the unnamed connection for you.

On Wed, 30 May 2007, Barry Rowlingson wrote:

> Prof Brian Ripley wrote:
>
>>
>> You could do this via a search_file() connection wrapper, but there is a
>> problem with ensuring connections get closed (which on.exit does here).
>>
>
> I'm not sure exactly what you mean by a 'search_file() connection
> wrapper', but I have realised that its probably a better idea to write a
> function that checks a search path for a file and then returns that file:
>
> search_file =
> function(name,path=options()$scanpath,...){
> for(p in path){
> file=file.path(p,name)
> if(file.exists(file)){
> return(file)
> }
> }
> return(name)
> }
>
> Then you can use that in any filename-using function:
>
> options(scanpath=c("/data1","/data2","/etc"))
>
> > search_file("passwd")
> [1] "/etc/passwd"
>
> > passwd = read.table(search_file("passwd"),sep=":")
> > record = scan(search_file("passwd"),what='')[1]
>
> Barry
>
> ______________________________________________
> R-help_at_stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Brian D. Ripley,                  ripley_at_stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________
R-help_at_stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 30 May 2007 - 11:39:03 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 30 May 2007 - 14:31:42 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.