57

I have a simple script file called test.R. It's saved in the working directory. When I go to File > Open > test.R, it opens the file in the editor (without executing the code, which is what I want).

How do I do this by typing a command in the console window? To be clear, I just want to open (not execute) the file.

nbro
  • 15,395
  • 32
  • 113
  • 196
user3654852
  • 753
  • 1
  • 5
  • 10

4 Answers4

98

You are looking for file.edit

file.edit('test.R')

should open the file in an editor (if you are in RStudio, this should default to RStudio)

nbro
  • 15,395
  • 32
  • 113
  • 196
mnel
  • 113,303
  • 27
  • 265
  • 254
14

It appears that if you are using RStudio then another option is to use rstudioapi::navigateToFile("test.R")

dpritch
  • 1,149
  • 13
  • 15
2

Another alternative is the shell.exec function.

shell.exec("text.R") # This will open the file or URL using the path associated with it

Also, I think for your use case. This code snippet might be a little bit useful.

file <- "example.csv"
sub_dir <- "subdirectory"
dir.create(sub_dir)
writeLines("myfile",file.path(sub_dir, file))
# Works
shell.exec(file.path(sub_dir, file, fsep = "\\"))
shell.exec(file.path(sub_dir, file))
Smart D
  • 131
  • 1
  • 3
2

I had the same issue that utils::file.edit() within my package opens outside R-studio. I changed it to usethis::edit_file(). With this function the file opens inside R-studio.

Anders Ellern Bilgrau
  • 9,928
  • 1
  • 30
  • 37
pbertens
  • 49
  • 4