How to set the current file location as the default working directory in R programming?

后端 未结 5 1095
执笔经年
执笔经年 2020-12-30 01:11

I want to make the current file location as the working directory.

Using Rstudio (Works!):

# Author  : Bhishan Poudel
# Program :         


        
5条回答
  •  旧巷少年郎
    2020-12-30 01:44

    The first answer I gave missed the point completely, since I hadn't looked closely upon what you wanted to achieve. The solution presented here should however do the trick.

    First note that source has an argument chdir that in the help-file is described with: logical; if TRUE and file is a pathname, the R working directory is temporarily changed to the directory containing file for evaluating.

    To manually specify that argument every time you want to source a file would be a pain, so let's add something to .Rprofile that changes the default value for chdir from FALSE to TRUE.

    The formals-function can be used to modify a default value, but when used upon a function that belongs to some other environment, the result will be that a local copy of the function will be created instead. That's not good enough.

    It's probably several ways to resolve this, but the following little hack of source did the trick for me when I inserted it into .Rprofile.

    .temporary_copy_source <- base::source
    formals(.temporary_copy_source)$chdir <- TRUE
    utils::assignInNamespace(
        x = "source",
        value = .temporary_copy_source,
        ns = environment(source))
    rm(.temporary_copy_source)
    

    A word of warning: The method presented here can in principle allow users to modify the default values of any argument in any function, but that would be an exceptionally bad idea to do. Keep in mind that your scripts might later on be shared with someone that doesn't have the same .Rprofile that you have. Never write code that requires such modifications of the namespaces!

提交回复
热议问题