Skip to content

24-7 Today

Menu
  • Home
  • Ads Guide
  • Blogging
  • Sec Tips
  • SEO Strategies
Menu

Little useless-useful R functions – Transforming dataframe to markdown table

Posted on March 26, 2023 by 24-7

[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)


Want to share your content on R-bloggers? click here if you have a blog, or here if you don’t.

Writing markdown documents outside RStudio (using the usual set of packages) has benefits and struggles. Huge struggle is transforming dataframe results into markdown table, using hypens and pipes. Ugghhh…

This useless functions takes R dataframe as input and prints out dataframe wrapped in markdown table.

iris[1:3,1:5]
# Result:
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa

And if we want this result in Markdown, it should look like:

 |Sepal.Length|Sepal.Width|Petal.Length|Petal.Width|Species|
 |---|---|---|---|---|
 |5.1|3.5|1.4|0.2|setosa|
 |4.9|3|1.4|0.2|setosa|
 |4.7|3.2|1.3|0.2|setosa|

This can be directly used in any editor. (Sidenote: if you decide to use Latex, same function can be created, just different ASCII chars needs to be used – ampersend and backslash).

The super lazy function 🙂

df_2_MD <- function(your_df){
  cn <- as.character(names(your_df))
  headr <- paste0(c("", cn),  sep = "|", collapse="")
  sepr <- paste0(c('|', rep(paste0(c(rep('-',3), "|"), collapse=""),length(cn))), collapse="")
  st <- "|"
    for (i in 1:nrow(your_df)){
      for(j in 1:ncol(your_df)){
        if (j%%ncol(your_df) == 0) {
          st <- paste0(st, as.character(your_df[i,j]), "|", "\n", "" , "|", collapse="")
        } else {
        st <- paste0(st, as.character(your_df[i,j]), "|", collapse="")
        }
      }
    }
  fin <- paste0(c(headr, sepr, substr(st,1,nchar(st)-1)), collapse="\n")
  cat(fin)
}  


# run function
short_iris <- iris[1:3,1:5]
df_2_MD(short_iris)

As always, code is available on Github in  Useless_R_function repository. The sample file in this repository is here (filename: Dataframe_to_markdown.R) Check the repository for future updates.

Happy R-coding and stay healthy!

Related

Related

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

©2025 24-7 Today | Design: WordPress | Design: Facts