I am looking for a way to test if R is being run from RStudio. For some reason I could find the answer on google yesterday but not today, but I think it had to do with testing if a certain system variable was set.
问题:
回答1:
There is no "running inside RStudio". RStudio is merely an IDE layer that wraps around R; at the end of the day it just launches the normal R executable you need to have on your $PATH anyway to operate RStudio.
As a proxy, and as R Studio You could test available.packages() for the 'manipulate' package though, or as a shorter version see if RStudio added itself to the .libPath()
content:
R> any(grepl("RStudio", .libPaths()))
[1] TRUE
R>
R>
回答2:
This is from ?rstudio
:
# Test whether running under RStudio
isRStudio <- Sys.getenv("RSTUDIO") == "1"
There is also rstudioapi::isAvailable()
, but checking this is not as reliable because RStudio doesn't seem to really need the rstudioapi
package to work correctly.
回答3:
Check the .Platform$GUI
option for "RStudio"
is.rstudio = function(){
.Platform$GUI == "RStudio"
}
See:
http://thecoatlessprofessor.com/programming/detecting-if-r-is-in-rstudio-and-changing-rstudios-default-graphing-device/
回答4:
When I start RStudio it seems to have tools:rstudio in position 2 on the search path. This has a function "RStudio.version" which is undocumented but seems to return the RStudio version string:
> RStudio.version()
[1] "0.96.316"
So you can define:
is.RStudio <- function(){
if(!exists("RStudio.version"))return(FALSE)
if(!is.function(RStudio.version))return(FALSE)
return(TRUE)
}
and maybe use that.
回答5:
To add to the number of nice guesses, here is a message from 2011 (Ice Age)
http://support.rstudio.org/help/discussions/problems/413-location-of-installed-packages
if (Sys.getenv("RSTUDIO_USER_IDENTITY")!= ""){
.libPaths(.Library) # Avoid additional libraries } else { # not rstudio ...
回答6:
I find the following works for me
checkRstudio <- function () {
return ("tools:rstudio" %in% search())
}
I am sort of new to R myself, but I believe Rstudio necessarily loads the package "tools:rstudio" in order to run.
回答7:
As of today, there are a few packages which include functions to check whether RStudio is running:
rstudioapi::isAvailable()
assertive::is_rstudio()
(list is non-exhaustive)
The assertive
and assertive.reflections
packages, resp., do include additional functions to check for other IDEs, desktop/server versions of RStudio, and various R
releases (e.g., alpha, beta, devel, release, patched, etc.)
回答8:
On a Mac only the Sys.getenv answer works
platform x86_64-apple-darwin10.8.0
version.string R version 3.1.0 (2014-04-10)
Sys.getenv("RSTUDIO")=="1" [1] TRUE
RStudio.version() Error: could not find function "RStudio.version"
any(grepl("RStudio", .libPaths())) [1] FALSE
.libPaths() [1] "/Library/Frameworks/R.framework/Versions/3.1/Resources/library"
回答9:
Neat solution is now available through the startup
package via the is_rstudio_console
function:
startup:::is_rstudio_console()
[1] TRUE