Say I have an R project opened at the following directory /home/user/workarea/project1
. Now I have a nested directory structure underneath and I am writing a function that is supposed to perform logging from anywhere inside this project and I want this function to write into files that are located at the directory /home/user/workarea/project1/log
. I plan to pass the file path as an argument to this function. Now I know that this file will always be located under the /log directory in the project's main directory - but how do I automatically find out which is my project directory, so that I don't always specify relative paths with ..
. I wouldn't want to hard-code my local path /home/user/workare/project1
, but be able to detect this wherever I clone my project.
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( ).
One of the great things about using RStudio Projects is that when you open a project it will automatically set your working directory to the appropriate location. You can check the file path of your working directory by looking at bar at the top of the Console pane.
The R project you create will come in the form of a folder containing a . Rproj file. This file is a shortcut and likely the primary way you will open your project. You can also open a project by selecting “Open Project” from the File menu.
A path is made up of folder names. If the path is to a file, then the path will ends with a file name. The folders and files of a path are separated by a directory separator (e.g., / or \ ). Different operating systems use different directory separators. In R, the function file.
It sounds like the rprojroot package will provide what you're looking for -- in particular, the find_rstudio_root_file()
function should provide what you need.
Also here::here()
would do the job in this case!
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