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

后端 未结 5 1090
执笔经年
执笔经年 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:39

    I write another answer because you changed your question. There are two useful facts:

    1. ofile is a variable in the environment of the source function, so you can use it only when you run some script with the source function.
    2. When you run a script from the terminal, then the working directory is set to the current directory in the terminal.

    So, to comment on your observations:

    1. Using Rstudio (Works!). Yes if you press Source (which usues the source function), but not if you press Run (which just runs the commands in the R console).
    2. Rscript writehere.r (Does not work!). That's because you are looking for ofile without a call to source.
    3. Rscript writehere.r (Works now!). Yes, but it works just by fact 2: the code this_dir <- function(directory) setwd( file.path(getwd(), directory) ) is needless as it is just the definition of a function called this_dir.
    4. Rstudio (Works!). First part: OK. Second part. It works just by fact 2. In particular setwd_thisdir is needless because it just prints the body of setwd_thisdir to the console.

    In summary setwd(dirname(parent.frame(2)$ofile)) is a useful trick when you source a script with the source function, but don't have access to the source function options: e.g. when you press Source in R-Studio. When possible use intead the source function with chdir=TRUE. If you run the script form the terminal just set the terminal to the script folder.

提交回复
热议问题