Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the absolute path of an input file in R

Tags:

r

I am using Rscript to plot some figures from a given CSV file in some directory, which is not necessarily my current working directory. I can call it as follows:

./script.r ../some_directory/inputfile.csv 

Now I want to output my figures in the same directory (../some_directory), but I have no idea how to do that. I tried to get the absolute path for the input file because from this I could construct the output path, but I couldn't find out how to do that.

like image 641
behas Avatar asked Nov 09 '12 15:11

behas


People also ask

How do I get the full path of a file in R?

If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path of the R script. To change the current working directory we need to use a function called setwd( ).

How do I find the absolute path of a file?

The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object. If the pathname of the file object is absolute then it simply returns the path of the current file object.

How do I find path of file in R?

To get the current directory, type getwd() . So try file. path and type getwd() to see whether it has an effect on the current directory.


2 Answers

normalizePath() #Converts file paths to canonical user-understandable form 

or

library(tools) file_path_as_absolute() 
like image 156
MattBagg Avatar answered Sep 24 '22 02:09

MattBagg


The question is very old but it still misses a working solution. So here is my answer:

Use normalizePath(dirname(f)). The example below list all the files and directories in the current directory.

dir <- "." allFiles <- list.files(dir) for(f in allFiles){   print(paste(normalizePath(dirname(f)), fsep = .Platform$file.sep, f, sep = ""))  } 

Where:

  • normalizePath(dirname(f)) gives the absolute path of the parent directory. So the individual file names should be added to the path.
  • .Platform is used to have an OS-portable code. (here)
  • file.sep gives "the file separator used on your platform: "/" on both Unix-alikes and on Windows (but not on the former port to Classic Mac OS)." (here)

Warning: This may cause some problems if not used with caution. For instance, say this is the path: A/B/a_file and the working directory is now set to B. Then the code below:

dir <- "B" allFiles <- list.files(dir) for(f in allFiles){   print(paste(normalizePath(dirname(f)), fsep = .Platform$file.sep, f, sep = ""))  } 

would give:

> A/a_file 

however, it should be:

> A/B/a_file 
like image 34
Azim Avatar answered Sep 25 '22 02:09

Azim