Identifying the OS from R

Sometimes a bit of R code needs to know what operating system it’s running on. Here’s a short account of where you can find this information and a little function to wrap the answer up neatly.

Operating systems are a platform issue, so let’s start with the constants in the list .Platform. For Windows the OS.type is just “windows”, but confusingly it’s “unix” for Unix, Linux, and my Mac OSX laptop. To be fair that’s because OSX is built on a base of tweaked BSD Unix. But it does seem that .Platform won’t distinguish OSX from a more traditional Unix or Linux machine.

Nor, by the way, will the value of GUI. When we’re running inside RStudio this is just “RStudio” and from the R.app that’s bundled with the R distribution it’s “AQUA” on OSX and “Rgui” on Windows. Worse, from my command line (Terminal) GUI is “X11″, even though it uses Aqua for the graphics instead. Presumably it’s this same value on Unix and Linux where we really would be using X11.

We can also ask about the R that we’re running by looking at the R.version list. On my machine this has os as “darwin13.4.0″, which is much the same information that Sys.info() presents more neatly.

Amusingly, the help page for R.version can’t quite decide whether or not we should use os to determine which operating system we’re running on: The ‘Note’ tells us not to use it, and the second piece of example code uses it anyway with a comment about it being a “good way to detect OSX”.

Another source of information is the Sys.info() function. On my machine it says that sysname is “Darwin”, which for various not very interesting reasons confirms that I’m running OSX. More straightforwardly, on Windows it’s “Windows” and on Linux it’s “Linux”. That all looks like what we want, except for the cryptic note in the Help pages suggesting that this function is not always implemented.

I’ve never used a machine where Sys.info() returned NULL. Have you?

To sum up then. The easiest way to find out what we want to know is to check Sys.info()["sysname"], remembering that “Darwin” means it’s OSX.

If we’re more cautious or we’re on a mystery machine where Sys.info really isn’t implemented, then we can first check whether .Platform$OS.type is “windows” or “unix” and if it’s “unix” look carefully at the R.version$os string. This backup route is a bit more involved, so I’ve wrapped everything up in a function that tries to return the lower case name of the operating system we’re running on.