Programmatically creating Markdown tables in R with KnitR

前端 未结 8 1739
梦谈多话
梦谈多话 2020-11-29 15:25

I am just starting to learn about KnitR and the use of Markdown in generating R documents and reports. This looks to be perfect for a lot of the day to day reporting that I

8条回答
  •  感情败类
    2020-11-29 15:58

    It is not very hard to make your own customized function. Here is a very simple proof of concept to generate an rmarkdown table of a data.frame:

       rmarkdownTable <- function(df){
          cat(paste(names(df), collapse = "|"))
          cat("\n")
          cat(paste(rep("-", ncol(df)), collapse = "|"))
          cat("\n")
    
          for(i in 1:nrow(df)){
            cat(paste(df[i,], collapse = "|"))
            cat("\n")
            }
        invisible(NULL)
        }
    

    In .Rmd document you would then use the function with results = 'asis':

    ```{r, results = 'asis'}
    rmarkdownTable <- function(df){
      cat(paste(names(df), collapse = "|"))
      cat("\n")
      cat(paste(rep("-", ncol(df)), collapse = "|"))
      cat("\n")
    
      for(i in 1:nrow(df)){
        cat(paste(df[i,], collapse = "|"))
        cat("\n")
        }
    invisible(NULL)
    }
    
    rmarkdownTable(head(iris))
    ```
    

    The code above would give you the following figure (in the example this is the pdf output, but since the table is in markdwon, you could knit into html or word too).

    enter image description here From here - and reading other people´s code - you can figure out how to manipulate the text to generate the table you want and create more personalized functions.

提交回复
热议问题