risks of using setwd() in a script?

前端 未结 6 2139
抹茶落季
抹茶落季 2020-12-04 15:59

I\'ve heard it said that it is bad practice to use setwd() in a script.

  • What are the risks/dangers associated with it?
  • What are bett
6条回答
  •  萌比男神i
    2020-12-04 16:24

    Though problems with setwd() have been targeted, I would like to add one more to the what are the alternatives part of the question. We often work with git where the relative path is very convenient

    setrelwd <- function(rel_path){
      curr_dir <- getwd()
      abs_path <- file.path(curr_dir,rel_path)
      if(dir.exists(abs_path)){
        setwd(abs_path)
      }
      else
      {
        warning('Directory does not exist. Please create it first.')
      }
    
    }
    
    > setrelwd("Summer2016")
    Warning message:
    In setrelwd("Summer2016") : Directory does not exist. Please create it first.
    

    Also if you don't want to see the warning message but create a folder right away see Check existence of directory and create if doesn't exist

提交回复
热议问题