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.
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( ).
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.
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.
normalizePath() #Converts file paths to canonical user-understandable form
or
library(tools) file_path_as_absolute()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With