Data frame to word table?

后端 未结 3 2124
一整个雨季
一整个雨季 2020-12-24 15:45

Is there a way to easily turn a data frame into a Word table via rmarkdown?

If I use rmarkdown in RStudio to create a Word document I get a nicely printed table but

3条回答
  •  温柔的废话
    2020-12-24 16:13

    You can use the rmarkdown and knitr packages. Here is an example function, where df is the data.frame, output_file is the output file name and output_dir the output folder. Extra named argument are sent to rmarkdown::render:

    df2word <- function(df, output_file = "table.doc", output_dir = ".", ...) {
      f <- tempfile(fileext =".Rmd" )
      cat(file = f, '```{r, echo = FALSE}
                      knitr::kable(df)
                     ```', append = TRUE)
      rmarkdown::render(f, output_file = output_file, output_dir = output_dir, ...)
      unlink(f)
      file.path(output_dir, output_file)
    }
    
    out <- df2word(mtcars)
    browseURL(out)
    

    Of course you can adapt the code to be more flexible.

    It is though flexible enough to allow you to extract other formats too, e.g. html:

    out <- df2word(mtcars, output_file = "table.html")
    browseURL(out)
    

    or pdf:

    out <- df2word(mtcars, output_file = "table.pdf", output_format = rmarkdown::pdf_document())
    browseURL(out)
    

提交回复
热议问题