0

I have a county data.R script where I am creating my primary df and a methods.Rmd where I would like to use that df. I would like to use the relative paths from my project and the getwd() confirmed the path, instead of creating a working directory like here, and it was correct. I was largely working off this tutorial. What am I missing here?

That script begins by loading the root data using the following.

county data.R

# read file
tf <- read.delim('data/cdc/suicide2017.txt')

If I run county data.R script by itself, tf is created fine. If I run the following in methods.Rmd I get an error.

methods.Rmd

```{r}
source('./county data.R')
source('./reference.R')

head(tf)```

Error:

cannot open file './data/cdc/suicide2017.txt': No such file or directoryError in file(file, "rt") : cannot open the connection

EDIT: Directory structure

-myproject
-r/
--scripts/
---county data.R
---methods.Rmd
-data/
--cdc/
---suicide2017.txt
Waylan
  • 37,164
  • 12
  • 83
  • 109
Jebediah15
  • 754
  • 3
  • 18
  • 39
  • 1
    If the file you read is placed in a path diverging from the parent directory (i.e. parent to the folder containing `methods.Rmd`), try `tf <- read.delim(file.path(getwd(), "../data/cdc/suicide2017.txt"))`. Go up two or more dir levels by adding `../` for each level. – NRLP Jan 22 '19 at 17:02
  • @Luminita Added directory for clarification. So would the correct syntax in `methods.Rmd` be `source('../r/scripts/county data.R')` Or do I need to change syntax in `county data.R` – Jebediah15 Jan 22 '19 at 17:13
  • The `country_data.R` is sourced correctly. Within the script `country_data.R` I would read `suicide2017.txt` as: `tf <- read.delim(file.path(getwd(), "../../data/cdc/suicide2017.txt"))`. – NRLP Jan 22 '19 at 17:21
  • Tried that and got: `cannot open file './county data.R': No such file or directoryError in file(filename, "r", encoding = encoding) : cannot open the connection` – Jebediah15 Jan 22 '19 at 17:34
  • I find this strange. When knitting the Rmd, the current working dir is set to the folder where the Rmd file is found. `source('./county data.R')` should work fine (from your question it seems it gets sourced correctly as the Error you indicate corresponds to a line of code from `county_data.R`. But according to the comment above it seems it stopped working. I wouldn't expect the solution you provide in the answer below to work. Did you in the meantime set another working directory in the .Rmd file before sourcing `county data.R`? – NRLP Jan 22 '19 at 19:26
  • Also, I realized that `getwd()` from `file.path(getwd(), "../../data/cdc/suicide2017.txt")` is redundant. `file.path("../../data/cdc/suicide2017.txt")` should normally work. – NRLP Jan 22 '19 at 19:31

1 Answers1

0

Thanks to @Luminita for directing me, I was one level too short. Posting answer in case someone in the future is as dumb as me.

methods.Rmd should be:

source('r/scripts/county data.R')

Jebediah15
  • 754
  • 3
  • 18
  • 39