Skip to content

Commit

Permalink
document how user code can check if it's running in RStudio
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinushey committed Feb 4, 2021
1 parent 4baeb39 commit 9d21f50
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions vignettes/r-session.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,38 @@ vignette: >
knitr::opts_chunk$set(eval = FALSE)
```


## Detecting RStudio

R code may need to determine whether it's being run within an RStudio session, versus a plain R session or something similar.

```{r eval=FALSE}
# check that RStudio is available via rstudioapi -- note that this must
# be checked prior to calling any other rstudioapi APIs!
if (rstudioapi::isAvailable()) {
# determine more information via
info <- rstudioapi::versionInfo()
# check for desktop mode
info$mode == "desktop"
# check for server mode
info$mode == "server"
# check the version of RStudio in use
info$version >= "1.4"
}
# check whether RStudio is running without relying on rstudioapi
.Platform$GUI == "RStudio" # NOTE: may be unreliable in .Rprofile
commandArgs()[[1]] == "RStudio"
```

A note: the `RSTUDIO` environment variable will be set both within the main RStudio session, but also within child processes launched by RStudio. If you need to specifically detect if your code is running within the main RStudio session, we recommend using an alternate mechanism.


## Session Interaction

The `rstudioapi` package allows you to interact with the running R session in a couple useful ways: you can send code to the R console, or restart the R session.
Expand All @@ -23,6 +55,7 @@ rstudioapi::restartSession(command = "print('Welcome back!')")
rstudioapi::sendToConsole("1 + 1", execute = TRUE)
```


## Running at Startup

Typically, code that you want to run at the start of an R session is placed into an `.Rprofile` file (see [Initialization at the Start of a Session](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Startup.html) for details). However, RStudio's API hooks are not available until RStudio has fully started up, so most `rstudioapi` methods will not work inside `.Rprofile`.
Expand Down

0 comments on commit 9d21f50

Please sign in to comment.