Valid file name in R

I want to get the full file name in R, given any standard notation. For example:

  • file.ext
  • ~ / file.ext (this case can be handled by path.expand )
  • ../current_dir/file.ext
  • and etc.

A fully qualified file name means, for example, (on a Unix-like system):

/home/user/some/path/file.ext

(Edited - use file.path and try Windows support) . A rough implementation may be:

 path.qualify <- function(path) { path <- path.expand(path) if(!grepl("^/|([AZ|az]:)", path)) path <- file.path(getwd(),path) path } 

However, I would ideally want something cross-platform that could handle relative paths using ../ , symbolic links, etc. The best solution would be only an R solution (instead of shell scripts or the like), but I cannot find any simple way to do this without considering it from scratch.

Any ideas?

+8
r filenames
source share
2 answers

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" 

On Windows, there is a winslash argument that you can set all the time, since it is ignored by nothing but Windows, so it does not affect other OSs:

 > normalizePath("./foo.R", winslash="\\") [1] "/home/gavin/tmp/bar/foo.R" 

(You need to avoid \ , therefore, \\ ) or

 > normalizePath("./foo.R", winslash="/") [1] "/home/gavin/tmp/bar/foo.R" 

depending on how you want the path to be presented / used. The first is the default ( "\\" ), so you can stick to this if that's enough, without having to explicitly specify.

In R 2.13.0, the bit "~/file.ext" also works (see comments):

 > normalizePath("~/foo.R") [1] "/home/gavin/foo.R" 
+10
source share

I think I missed the point of your question, but I hope my answer can point you in the direction you need (it combines your idea of ​​using paste and getwd with list.files ):

 paste(getwd(),substr(list.files(full.names = TRUE), 2,1000), sep ="") 

Edit: Works with windows in some checked folders.

+2
source share

All Articles