Programmatically creating Markdown tables in R with KnitR

前端 未结 8 1735
梦谈多话
梦谈多话 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:35

    My function for Gitlab:

    to_markdown<-function(df) {
        wrap<-function(x,sep=" ") paste0("|", sep, paste(x, collapse=paste0(sep,"|",sep)), sep, "|", sep=sep)
        paste0(wrap(colnames(df)),
        "\n",
        wrap(rep("------", ncol(df)),sep=""),
        "\n",
        paste(apply(df, 1, wrap), collapse="\n"))
    }
    
    cat(to_markdown(head(iris[,1:3])))
    
    | Sepal.Length | Sepal.Width | Petal.Length | 
    |------|------|------|
    | 5.1 | 3.5 | 1.4 | 
    | 4.9 | 3 | 1.4 | 
    | 4.7 | 3.2 | 1.3 | 
    | 4.6 | 3.1 | 1.5 | 
    | 5 | 3.6 | 1.4 | 
    | 5.4 | 3.9 | 1.7 | 
    

提交回复
热议问题