快速回到R project所在的工作目录

RstudioRproject可以用来方便的管理自己的某个项目的所有代码,文件等等.另外的一个好处是打开该项目文件之后,路径自动设置为该project所在的工作目录,因此在该项目下可以通过相对路径来设置后续分析文件所在的工作目录.从未方便代码的移植和分享.

但是如何快速回到自己Rproject所在的目录呢?比如在某个项目中,我的Rproject所在目录为A,而我的某个数据分析的文件在路径A/B/C,当我通过相对路径设置在该目录下,另外一个分析所在的目录为A/E/F,这时候我就需要先将路径设置到A,然后才可以再通过设置相对路径将目录修改为A/E/F.所以可以看到,需要经常将目录设置为Rproject所在的根目录.因此,写了一个小的函数,可以用来快速的目录切换为Rproject所在目录.

代码如下:

setwd_project <- function() {
  currect_wd <-
    getwd()

  candidate_wd <-
    currect_wd %>%
    stringr::str_split("/") %>%
    unlist()

  if (length(candidate_wd) == 1) {
    candidate_wd <- currect_wd
  } else{
    candidate_wd <-
      lapply(2:length(candidate_wd), function(i) {
        paste(candidate_wd[1:i], collapse = "/")
      })
  }

  candidate_wd <-
    rev(candidate_wd)

  for (i in 1:length(candidate_wd)) {
    wd <- candidate_wd[[i]]
    file_name <-
      list.files(wd,
                 recursive = ifelse(wd == currect_wd, TRUE, FALSE),
                 full.names = TRUE)
    project_index <-
      grep(".Rproj", file_name)

    if (length(project_index) != 0) {
      project_wd <-
        file_name[project_index[1]] %>%
        stringr::str_split("/") %>%
        unlist() %>%
        head(-1) %>%
        paste(collapse = "/")
      cat(
        "The project name is:",
        file_name[project_index[1]] %>%
          stringr::str_split("/") %>%
          unlist() %>%
          tail(1),
        "\n"
      )
      cat("The project wd is:",
          project_wd, "\n")

      setwd(project_wd)
      break()
    }
  }
  if (length(project_index) == 0) {
    cat("There are no .Rproj in your file. No change for wd.\n")
  }
}

思路和代码都很简单,这个函数也在我自己常用的小工具集合sxtTools包中,所过想要直接使用,可以考虑安装这个包.

devtools::install_github("jaspershen/sxtTools")
Avatar
Xiaotao Shen
Postdoctoral Research Fellow

Metabolomics, Multi-omics, Bioinformatics, Systems Biology.

Related

Next
Previous
comments powered by Disqus