library(cctu)
library(magrittr)
library(knitr)

PATH_figure <- file.path(getwd(), "Output", "Figures")

meta_table <- read.csv(file = file.path("Output", "meta_table.csv"),
                       stringsAsFactors = FALSE,
                       colClasses = "character")
index <- order_dewey(meta_table$number)
meta_table <- meta_table[index, ]
rm(index)

sections <- unique(meta_table$section)
src <- as.character(NULL)
for (sect in sections) {
  src <- c(src, paste("\n#", sect))
  subtab <- subset(meta_table, section == sect)
  for (row in 1:nrow(subtab)) {
    src <- c(src, paste("\n##", subtab[row, "number"], 
                        subtab[row, "title"], "\nPopulation:",
                        subtab[row, "population"]))
    if (!is.na(subtab[row, "subtitle"])) {
      src <- c(src, paste("\nSubtitle:", subtab[row, "subtitle"]))
    }

    if (subtab[row, "item"] %>% tolower() == "table") {
      file_name <- file.path("Output", "Core", 
                             paste0("table_", subtab[row, "number"], ".xml"))
      # knit exapnd really doesn't like absolute paths or \ or \\
      if (file.exists(file_name)) {
        src <- c(
          src,
          knitr::knit_expand(
            file = file.path("Progs", "_table.Rmd") %>% normalizePath(),
            chunk_name = paste0("table", subtab[row, "number"]),
            file_name = file_name
          )
        )
      }
    }


    if (subtab[row, "item"] %>% tolower() == "text") {
      file_name <- paste0("Output/Core/text_", subtab[row, "number"], ".xml")
      # knit exapnd really doesn't like absolute paths or \ or \\
      if (file.exists(file_name)) {
        src <- c(
          src,
          knitr::knit_expand(
            file = "Progs/_text.Rmd" %>% normalizePath(),
            chunk_name = paste0("text", subtab[row, "number"]),
            file_name = file_name
          )
        )
      }
    }


    if (subtab[row, "item"] %>% tolower() == "figure") {
      file_name <- file.path(PATH_figure,
                             paste0("fig_", subtab[row, "number"], ".png"))
      if (file.exists(file_name)) 
        src <- c(src, paste0("![](", file_name, ") \n"))
    }
    if (!is.na(subtab[row, "footnote1"])) {
      src <- c(src, paste("\n", subtab[row, "footnote1"]))
    }
    if (!is.na(subtab[row, "footnote1"])) {
      src <- c(src, paste("\n", subtab[row, "footnote2"]))
    }
  }
}

r knitr::knit_child(text = src, envir = parent.frame())



shug0131/cctu documentation built on June 12, 2025, 10:37 p.m.