sitems
sitems

Reputation: 788

Detect OS and change the path appropriately in R

I have two operating systems installed on my computer - windows and linux. When I write my scripts in windows and then I try to run them on linux, I have to change every path.

For example, to set my working directory in windows, I have to type setwd("d://MyStatistics").

However, in linux, this command is setwd("/media/55276F9D5951EC83/MyStatistics").

Is it possible to automatically detect current operation system and change the path if it is from the other system?

Upvotes: 2

Views: 2083

Answers (3)

ping
ping

Reputation: 1336

You could potentially achieve your "one path fits all" aim easily if both systems have the same sets of folders in one place (edit: just re-read the question, and since your talking about one computer, this should be the case). You could then either set that location as the working directory at the beginning of your script, using a method like Roland's answer, or make it the default directory that R opens with by adding it to Rprofile.site in each OS. You could then just set working directories by pasting to the initial directory.

Something like:

#add line to Rprofile.site for both OS
setwd("/path/to/folder/containing/data/folders")

then in the script:

starting.directory = getwd() #at beginning of script
setwd(paste0(starting.directory, "/MyStatistics")) 

You could also add "starting.directory" as an object in Rprofile.site instead:

#add line to Rprofile.site for both OS
starting.directory <- "/path/to/folder/containing/data/folders"

then use the same paste0 as above.

You could also alter Rprofile.site in both OS to contain objects with names of various working directories, which point to the same folder with OS specific paths so that they can just be referred to as "setwd(myStatsDirectory)", and pasted to as above. Maybe the best way is to do something like that for every drive you'd like to be able to use with both systems, so you could do something like:

setwd(D.Drive)
setwd(paste0(D.Drive, "/folder1/folder2/etc"))

(edit: this is a similar method to Simon O'Hanlon's comment on Roland's answer, using tilde with the home directory)

Upvotes: 0

Roland
Roland

Reputation: 132726

Use an if condition which tests R.version$platform or .Platform$OS.typ.

# It's as simple as...
path <- "/media/55276F9D5951EC83/MyStatistics"
if( .Platform$OS.type == "windows" )
  path <- "d:\\MyStatistics"

setwd( path )

Upvotes: 3

Balu
Balu

Reputation: 2447

This link would be helpfull.

Sys.info() returns details of the platform R is running on

Upvotes: 2

Related Questions