Search code examples
rdirectoryfilepath

Always setting path across users in R


I have a simple question, how does one always set the same path across a user base. For instance, I use getwd() to get my path: "C:/Users/Genetics/Documents". Can I set in my script, no matter who uses this to go to "C:/Users/Any User/Desktop"? I want to make this fluid, so I don't have correct this for each person.

ALWAYS_TO_DEKSTOP<- Some way to be flexible to Desktop across users and systems???
PathName <- paste(ALWAYS_TO_DEKSTOP,"BIDS/IDs.txt", sep="");
read.table(PathName, header=T);

Solution

  • You can use file.path(Sys.getenv("USERPROFILE") to get the path to the users home directory. Then append the folder you want, e.g. Documents so you get

    file.path(Sys.getenv("USERPROFILE"),"Documents")
    [1] "C:\\Users\\my_username/Documents"
    

    Notice the escaped backslashes on Windows. You can change that with normalizePath(), see ?normalizePath for reasons why you might want that.

    normalizePath(path = file.path(Sys.getenv("USERPROFILE"),"Documents"), winslash = "/")
    [1] "C:/Users/my_username/Documents"
    

    There are other paths available in Sys.getenv(), such as (on Windows)

    ProgramData                                    C:\ProgramData
    ProgramFiles                                   C:\Program Files
    ProgramFiles(x86)                              C:\Program Files (x86)
    RTOOLS40_HOME                                  C:\rtools40