Setting up a R notebook working directory in a R Project

Community

I've started using R Projects (really like them) but I have an issue understanding setting up my working dir in R Notebooks within a R Project.

I set my working dir in my setup R chunk as follows:

knitr::opts_knit$set(root.dir ="../")

And then when I deed to call a data set from my Data dir in the R projects I'll use something like

my_Dat <- read.csv("Data/mydata.csv")

which only seems to work when i knit the file. if I try running the code separately within the R Notebook I get an error

Error in file(file, "rt") : cannot open the connection

But if I change the code to my_Dat <- read.csv("../Data/mydata.csv") I can run the chunk, but then when I try and knit the code I get the following error

Line xxx Error in file(file, "rt") : cannot open the connection
Calls: ... withVisible -> eval -> eval -> read.csv -> read.table -> file
Execution halted

So what am I doing wrong??

Jeff

Hi, maybe using read.csv(here::here("Data/mydata.csv"))? This will make the project folder the root of all of your paths, making it consistent when knitting and running the code interactively

The "here" function I've just stared to read about it. Would I still need to set the working dir in my setup r chunk

With here you should be able to avoid having to do any r chunk setup.

Hi,

you can find some more information on Working directory with R Markdown in the Cookbook

If you have read it, that could be helpful. It will also show you the configuration you can made in the IDE.

you usually don't have to setup the working directory unless in very specific situation. For data loading and such, the here package adviced above is the solution IMO.

Just wanted to chime in to give some precisions :slight_smile:

Thanks @edgararuiz for the replies !

here::hear seem to work and it appears I don't need to set the working dir in my setup chunk. Habit from creating stand along R Notebooks. But I'm finding the project files are a lot more useful . Thanks

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.