R code may need to determine whether it’s being run within an RStudio session, versus a plain R session or something similar.
# 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
<- rstudioapi::versionInfo()
info
# check for desktop mode
$mode == "desktop"
info
# check for server mode
$mode == "server"
info
# check the version of RStudio in use
$version >= "1.4"
info
}
# check whether RStudio is running without relying on rstudioapi
$GUI == "RStudio" # NOTE: may be unreliable in .Rprofile
.PlatformcommandArgs()[[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.
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.
# restart R, then run some code after
::restartSession(command = "print('Welcome back!')")
rstudioapi
# send some code to the console and execute it immediately
::sendToConsole("1 + 1", execute = TRUE) rstudioapi
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 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
.
If you want to invoke rstudioapi
methods on session
startup, use the rstudio.sessionInit
hook. For example, to
print the RStudio version to the R console when the session begins:
setHook("rstudio.sessionInit", function(newSession) {
if (newSession)
message("Welcome to RStudio ", rstudioapi::getVersion())
action = "append") },