Fully qualified file name in R
I wish to get the fully qualified name of a file in R, given any of the standard notations. For example:
- file.ext
- ~/file.ext (this case can be handled by
path.expand
) - ../current_dir/file.ext
- etc.
By fully qualified file name I mean, for example, (on a Unix-like system):
/home/user/some/path/file.ext
(Edited - use file.path and attempt Windows support) A crude implementation might be:
path.qualify <- function(path) {
path <- path.expand(path)
if(!grepl("^/|([A-Z|a-z]:)", path)) path开发者_运维百科 <- file.path(getwd(),path)
path
}
However, I'd ideally like something cross-platform that can handle relative paths with ../
, symlinks etc. An R-only solution would be preferred (rather than shell scripting or similar), but I can't find any straightforward way of doing this, short of coding it "from scratch".
Any ideas?
I think you want normalizePath()
:
> setwd("~/tmp/bar")
> normalizePath("../tmp.R")
[1] "/home/gavin/tmp/tmp.R"
> normalizePath("~/tmp/tmp.R")
[1] "/home/gavin/tmp/tmp.R"
> normalizePath("./foo.R")
[1] "/home/gavin/tmp/bar/foo.R"
For Windows, there is argument winslash
which you might want to set all the time as it is ignored on anything other than Windows so won't affect other OSes:
> normalizePath("./foo.R", winslash="\\")
[1] "/home/gavin/tmp/bar/foo.R"
(You need to escape the \
hence the \\
) or
> normalizePath("./foo.R", winslash="/")
[1] "/home/gavin/tmp/bar/foo.R"
depending on how you want the path presented/used. The former is the default ("\\"
) so you could stick with that if it suffices, without needing to set anything explicitly.
On R 2.13.0 then the "~/file.ext"
bit also works (see comments):
> normalizePath("~/foo.R")
[1] "/home/gavin/foo.R"
I think I kind of miss the point of your question, but hopefully my answer can point you into the direction you want (it integrates your idea of using paste
and getwd
with list.files
):
paste(getwd(),substr(list.files(full.names = TRUE), 2,1000), sep ="")
Edit: Works on windows in some tested folders.
精彩评论