save rmarkdown output in different folder

How to save the output in other dynamic folder

title: "Untitled"
date: "5/31/2020"
output: word_document

knitr::opts_chunk$set(echo = TRUE)

R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)

Including Plots

You can also embed plots, for example:

plot(pressure)

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

See question how can i create a pdf file with different name from rmd.

1 Like

I want to use command inside rmd file.

Can I know how to edit this function
knit: (function (...) { your_knit_function(...) })

If you install the HOQCutil package from GitHub you can use the function HOQCutil::my_knit in your YAML the following way:

---
hoqc_output: ./output/new1_name 
knit: (function (...) { source('myknit.R'); myknit(...) })
...
output: html_document
---

This will create a subfolder output if necessary and place the output in that folder under the name new1_name.html .

If you only need the functionality to change the output name or folder you can also use the functions below. Just copy them in your folder in the file myknit.R and use the following YAML:

---
hoqc_output: ./output/new2_name 
knit: (function (...) { source('myknit.R'); myknit(...) })
...
output: html_document
---

The two functions to copy (with the same MIT License as the package) are the following:

myknit <-
  function (inputFile,
            encoding = getOption("encoding"),
            hoqc_render = TRUE,
            clean = TRUE) {
    
    # Acknowledgement: idea comes from
    # https://stackoverflow.com/questions/39885363/importing-common-yaml-in-rstudio-knitr-document
    # This is abbreviated version of HOQCutil::myknit
    
    # read in the src file
    rmd <- readLines(inputFile)
    # the line numbers of the start and end line for the yaml section
    yaml_ind <- stringr::str_which(rmd, '^---$')[1:2]
    # retrieve the yaml metadata block
    yaml <- rmd[do.call(seq.int, as.list(yaml_ind))]
    # first document type determines the output type
    doctype_line <-
      c(stringr::str_subset(yaml, 'pdf_document|html_document'),
        'html_document')[1]
    doc_type     <- stringr::str_match(doctype_line, '(pdf|html)_document')[1, 2]
    # search hoqc_output
    values     <- list()
    ix = stringr::str_which(yaml,'^hoqc_output')
    if (length(ix)>0) {
      ix = ix[1]
      a = stringr::str_squish(yaml[ix])
      a = stringr::str_extract(a,"(?<=hoqc_output).+") 
      a = stringr::str_extract(a,"[^: ]{1,3}(.+)$") 
      a = stringr::str_remove_all(a,"[\"']") 
      values[['hoqc_output']] <- a
    }
    # determine output name for pdf or html file
    if (!is.null(values[['hoqc_output']])) {
      hoqc_output = values[['hoqc_output']]
      hoqc_output = myknit_force_ext(hoqc_output, doc_type)
    } else {
      inputFileb <- strsplit(inputFile, '.', fixed = T)[[1]][1]
      hoqc_output = myknit_force_ext(inputFileb, doc_type)
    }
      ofile <-
        rmarkdown::render(
          inputFile,
          encoding = encoding,
          output_file = hoqc_output,
          envir = new.env(),
          clean = clean
        )
  }

myknit_force_ext <- function (filename, doc_type, tf=T, suffix='') {
  # optionally give an extension or suffix to filename
  # ensure tf becomes a logical variable
  tf1       <- as.logical(tf)
  if (is.na(tf1))
    tf1 = switch(tolower(tf), yes = T, no = F, T)
  # do not consider path
  filename1 <- basename(filename)
  dirname1  <- dirname(filename)
  # split proper name and extension
  ibe <-  strsplit(filename1, '.', fixed = T)
  # unpack the list
  ibe <- ibe[[1]]
  # append suffix to proper name
  ibe[1] <- paste0(ibe[[1]][1], suffix)
  # if extension is required add the given one (will only be used when length(ibe) ==1)
  if (tf1 == TRUE)
    ibe <-  c(ibe, doc_type)
  # new filename
  if (length(ibe) < 2)
    newname <- ibe
  else
    newname <- paste(ibe[1:2], collapse = '.')
  # ensure that folders exist and retrieve the full name
  `%>%` <- magrittr::`%>%`
  newname <- paste(dirname1, newname, sep = '/')
  newname %>% fs::path_dir() %>% fs::dir_create()
  already_there <- fs::file_exists(newname)
  newname %>% fs::file_create() %>% fs::path_real() %>% as.character() -> newname
  newname
}

I read about https://bookdown.org/yihui/rmarkdown-cookbook/custom-knit.html

knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, output_file = "x.docx",
output_dir = "C:/")
})
however i got an error
Error in convert(output_file, run_citeproc) :
failed to copy rendered pandoc artefact to 'C://x.docx'
Calls: -> -> convert
Execution halted

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.