Working with knitr using subdirectories

后端 未结 2 1256
逝去的感伤
逝去的感伤 2020-12-28 16:31

I have a project folder, which is my working directory. Let\'s call it project. Under the project folder are 4 subdirectories: code,

相关标签:
2条回答
  • 2020-12-28 16:48

    I use this approach. Place this at the start of your rmd file, and you will be able to use run code in line and using an RStudio project setup. The trick is to reset the knitr home directory to your project directory (mine is a couple in from the project directory hence the '/../../' but you get the idea). You also need to reset the figure and cache pathways otherwise outputs will end up in strange places.

    If you play around with the setup below you can create the right file structure for your project needs.

    ```{r setup, include=FALSE}
    ###--- Update the knitr working directory (R works from the project folder, knitr works in the rmd folder)
    dd <- getwd()
    knitr::opts_knit$set(root.dir= paste(dd,'/../../')) 
    
    ###--- Set some knitr defaults for all of the code blocks below. 
    knitr::opts_chunk$set(warning=FALSE
                          ,error=FALSE
                          ,message=FALSE
                          ,cache=F
                          ,eval=TRUE
                          ,results='asis'
                          ,echo=TRUE
                          ,fig.ext="png"
                          ,cache.path = paste0(dd,'/cache/')
                          ,fig.path = paste0(dd,'/figures/')
                          ) 
    ```
    
    0 讨论(0)
  • 2020-12-28 16:52

    Try this. It assumes you have the 4 folders you listed inside the working directory project. It also assumes you have a .csv file called myData.csv in data.

    When you knit the file, the plot will be saved in figures. At the end, the code looks for html files in code and moves them to documents. There's probably a better way to do this.

    ```{r setup}
      library(knitr)
      opts_knit$set(root.dir=normalizePath('../'))
      opts_chunk$set(fig.path = "../figures/", dev='pdf') # corrected path and added dev
    ```
    
    ```{r import}
      dat <- read.csv("data/myData.csv")
    ```
    
    ```{r plot}
      # pdf(file="figures/test.pdf")  # I do this in setup instead
      plot(dat)
      # dev.off()
    ```
    
    ```{r move}
      files <- list.files("code/")
      index <- grep("html", files)
      file.rename(file.path("code", files[index]),
                  file.path("documents", files[index]))
    ```
    
    0 讨论(0)
提交回复
热议问题