Reputation: 233
How can I read from a file in R when I have only a part of its name including starting or ending characters?
Thanks
Upvotes: 2
Views: 499
Reputation: 94202
There is also Sys.glob
which will expand patterns using stars and question marks according to glob
syntax.
Here it is wrapped in a function to match filenames of the form "first*last"
where "*"
is anything. If you really have stars or other special chars in your filename... then you need to do a bit more.. Anyway:
> match_first_last = function(first="", last="", dir=".")
{Sys.glob(
file.path(dir,paste(first,"*",last,sep=""))
)
}
# matches "*" and so everything:
> match_first_last()
[1] "./bar.X" "./foo.c" "./foo.R"
# match things starting `foo`
> match_first_last("foo")
[1] "./foo.c" "./foo.R"
# match things ending `o.c`
> match_first_last(last="o.c")
[1] "./foo.c"
# match start with f, end in R
> match_first_last("f","R")
[1] "./foo.R"
Upvotes: 0
Reputation: 9344
You can use list.files
, which has a pattern
argument, to try to match as close as you can.
writeLines(c('hello', 'world'), '~/tmp/example_file_abc')
filename <- list.files(path = '~/tmp', pattern = 'file_abc$', full.names = TRUE)[1]
readLines(filename)
# [1] "hello" "world"
Upvotes: 5