1

I'm trying to open a file that does not exist in my current directory. This file is named testFile.r existing in the data folder in my current directory. I tried file.path("./data") and then wanted to show the file with this command file.show("testFile.r") but it gives this error:

Error: File testFile.r does not exist.

And the command getwd() gives the previous current directory. So any thoughts on this?

ezzeddin
  • 499
  • 2
  • 5
  • 25
  • Just use `setwd()` –  Apr 12 '18 at 17:17
  • Possible duplicate of [R command for setting working directory to source file location](https://stackoverflow.com/questions/13672720/r-command-for-setting-working-directory-to-source-file-location) –  Apr 12 '18 at 17:19
  • Thank you, but I need to keep both directories because I can switch between them easily. Is there a way like `addpath` in MATLAB ? – ezzeddin Apr 12 '18 at 17:36
  • What does "keep both directories" mean? You could do `old_dir <- getwd(); setwd(new_dir);` and then `getwd(old_dir)` later on, if that is what you want. –  Apr 12 '18 at 17:38
  • Suppose I have more than two directories. Is there a vector that can contain multiple directories so that I can just concatenate what I need because I'm too lazy to store the old directories. But anyways your answer is simple and I can do it but I prefer something like `addpath` in MATLAB or `sys.path.append()` in python. – ezzeddin Apr 12 '18 at 19:25
  • Check out `.libpaths` for setting the paths to R libraries, but this is not the same as setting the working directory, which can only be a single path on any OS known to me. –  Apr 13 '18 at 12:46

1 Answers1

0

You change your current directory using the command setwd(new_directory) (replacing new_directory with the path to the directory you want).

If you'd rather stay in your current directory, just do

file.show("./data/testFile.r")

To keep track of multiple paths, you can save each as a variable and use the paste function to reference the file:

path1 <- "./data/"
path2 <- "./second_folder_name/"
file.show(paste0(path1, "testFile.R"))
file.show(paste0(path2, "testFile.R"))
Melissa Key
  • 4,476
  • 12
  • 21
  • Thank you, but I need to keep both directories because I can switch between them easily. Is there a way like `addpath` in MATLAB ? – ezzeddin Apr 12 '18 at 17:35
  • I'm not familiar with MATLAB, so I can't address this directly. However, you can easily save the path as a text. I'll edit my answer accordingly. – Melissa Key Apr 12 '18 at 18:15