I was wondering how to automatically detect operating system in R, for example to place things in the .Rprofile.
Asked
Active
Viewed 1.0k times
62
-
2related: http://stackoverflow.com/questions/2096473/r-determine-if-a-script-is-running-in-windows-or-linux but the answers below are more complete. – JD Long Dec 16 '10 at 18:26
4 Answers
116
switch(Sys.info()[['sysname']],
Windows= {print("I'm a Windows PC.")},
Linux = {print("I'm a penguin.")},
Darwin = {print("I'm a Mac.")})
Since it took me more than a trivial amount of time to sort this out, I thought other would benefit as well.
Regards,
- Brian

Marek
- 49,472
- 15
- 99
- 121

Brian G. Peterson
- 3,531
- 2
- 20
- 21
46
I'm not sure about using Sys.info()
since the help page says it is not implemented on all R platforms; maybe use .Platform
instead? ?.Platform
has a lot of useful information, since:
‘.Platform’ is a list with some details of the platform under which R was built. This provides means to write OS-portable R code.
It also seems the packages included with R use .Platform
much more frequently than Sys.info
.
josh: /c/R/R-2.12.0-src/src/library
> grep ".Platform" */R/* | wc -l
144
josh: /c/R/R-2.12.0-src/src/library
> grep ".Platform\$OS.type" */R/* | wc -l
99
josh: /c/R/R-2.12.0-src/src/library
> grep "Sys.info" */R/* | wc -l
4

Joshua Ulrich
- 173,410
- 32
- 338
- 418
6
> Sys.info()
sysname
"Linux"
release
"2.6.32-26-generic"
version
"#48-Ubuntu SMP Wed Nov 24 09:00:03 UTC 2010"

Spacedman
- 92,590
- 12
- 140
- 224
-
2There's also `R.version$os` but `Sys.info()` is better for testing against. – Richie Cotton Dec 16 '10 at 16:45
-
-
5The help page for `R.version` says "Do not use `R.version$os` to test the platform the code is running on: use `.Platform$OS.type` instead." Annoyingly, it doesn't mention the suitability of `Sys.info()`. – Richie Cotton Jun 22 '12 at 15:11
5
Since Sys.info()
and .Platform$OS.type
produce differing results depending upon which OS is running, I searched some more and found the following function at https://www.r-bloggers.com/identifying-the-os-from-r/
get_os <- function(){
sysinf <- Sys.info()
if (!is.null(sysinf)){
os <- sysinf['sysname']
if (os == 'Darwin')
os <- "osx"
} else { ## mystery machine
os <- .Platform$OS.type
if (grepl("^darwin", R.version$os))
os <- "osx"
if (grepl("linux-gnu", R.version$os))
os <- "linux"
}
tolower(os)
}

mhminai
- 51
- 1
- 1