[R] search path question
Prof Brian Ripley
ripley at stats.ox.ac.uk
Wed May 30 13:32:11 CEST 2007
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
More information about the R-help
mailing list