【问题标题】:How to generate full qmd file from child files?如何从子文件生成完整的 qmd 文件?
【发布时间】:2023-01-31 21:40:46
【问题描述】:

我有一个包含多个子文档的四开本文件。我可以把它们渲染得很好。 但我想生成一个包含完整文档的 qmd 文件。 所以基本上我需要某种 qmd 到 qmd 转换器。有没有办法做到这一点?

像这样的部分插入孩子:

```{r}
#| label = "child1",
#| eval = TRUE,
#| child = "child1.qmd"
```

【问题讨论】:

    标签: r-markdown quarto


    【解决方案1】:

    似乎没有人有一个“好的”解决方案。所以这里有一个“手动”把东西放在一起的技巧。 它找到定义了子项的代码块,并用引用子项中的文本替换该代码框。

    merge_children <- function(file, path_prefix, outpath, child_pattern = "[[:blank:]]*#\|[[:blank:]]*child[[:blank:]]*=.*,+[[:blank:]]*", child_capture = "[[:blank:]]*#\|[[:blank:]]*child.*=.*,+[[:blank:]]*"){
      # read file
      txt <- readLines(file)
      
      # find children
      child_defs <-  txt %>% grep(child_pattern,.)
      
      
      # find children paths
      child_paths <-  map_chr(child_defs,  function(x){
                                                        txt[x] %>% 
                                                        gsub(child_capture,"\1", .) %>% 
                                                        gsub('.*\"(.*)\".*',"\1", .)
                                                      }
                             )
    
      
      if(length(child_paths)==0){
        
        writeLines(txt, outpath)
        return(message("No children found. Will just copy file."))
        }
      
      
      child_paths <- paste0(path_prefix, child_paths)
      
      
      #find start and end of relevant code sections
      code_start <- txt %>% grep("^[[:blank:]]*```\{r.*",.)
      code_end   <- txt %>% grep("^[[:blank:]]*```[[:blank:]]*$",.)
      
      # read children
      txt_children <- map(child_paths, readLines)
      
      indeces <- sort(c(1, code_start, code_end+1))
      
      txt_split <- split(txt, rep(seq(indeces), diff(c(indeces, length(txt)+1))))
      
      has_child <-  map_lgl(txt_split, ~any(grepl(child_pattern,..1))) %>% as.vector %>% which
      
      # replace children
      if(length(has_child) != length(txt_children)) stop("children replacement indeces not equal to amount of children")
      
      txt_split[has_child] <- txt_children
      
      # put back together
      txt_new <- txt_split %>% unlist()
    
      
      writeLines(txt_new, outpath)
      
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 2018-04-21
      • 2012-05-20
      • 2018-11-10
      相关资源
      最近更新 更多