Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Rstudio relative paths

Tags:

path

r

rstudio

How can I use relative paths in a RStudio project environment?

For example, to access a file, I use the whole path:

# My RStudio project working directory:  getwd() [1] "C:/Users/MaurizioLocale/OneDrive/Data_Science/10_Capstone_project/      CP_Natural_Language/MY_FILE.txt" 

But it is really long.

I am trying to use paths relative to the working environment. I tried something conceptually similar to:

"~/MY_FILE.txt" 

where ~ represents the working environment. Unfortunately, it does not work.

like image 463
Worice Avatar asked Apr 25 '16 07:04

Worice


People also ask

How do I get the full path 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( ).


2 Answers

You could change the working directory. Get the address in the beginning getwd(), replace it by your project folder with setwd(). Then, when accessing a file just use read.table("./folder/file.R").

like image 115
user3507584 Avatar answered Sep 30 '22 04:09

user3507584


The so-called here package is really useful for avoiding absolute paths in (as well as outside of) RStudio. Suppose you have an RStudio project and want to access the file /data/file.txt. This would be done as follows. This way, you don't have to mess around with getwd(), just work relative to your project root using here().

library(here) #> here() starts at C:/test/someproject here("data", "file.txt") #> "C:/test/someproject/data/file.txt" readLines(here("data", "file.txt")) #> "The here package is awesome!" 

How here figures out where your project root is is described in ?here and also in the "Ode to the here package" by Jenny Bryan.

like image 23
hplieninger Avatar answered Sep 30 '22 04:09

hplieninger