Home > Software design >  How to create a table on a Stack Overflow question/answer from a R dataframe object?
How to create a table on a Stack Overflow question/answer from a R dataframe object?

Time:06-21

I am aware of the syntax to create a table on Stack Overflow, but is there any function that takes a dataframe as argument and that copies the table to the clipboard, so that it can be pasted on Stack Overflow?

# Any function that takes a dataframe as an argument 
# and that copies the table to the clipboard
table_to_clipboard(df) # ???

# Then I could paste the result (Ctrl   V)

|      Heading 1      |     Heading 2    |
|---------------------|------------------|
|          12         |         34       |
|          99         |         42       |
Heading 1 Heading 2
12 34
99 42

CodePudding user response:

You can get such a table with the help of the pander package:

dat <- iris[1:3, ]
library(pander)
pandoc.table(dat, style = "rmarkdown")

| 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  |
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

To get it in the clipboard:

library(clipr)
write_clip(pandoc.table.return(dat, style = "rmarkdown"))
  • Related