使用 dput 从 R 环境中将 table 转换为 .md 格式

Get a table from R environment into .md format with dput

我正在创建几个我想包含在 .md 中的输出。我无法控制选择 .md 格式(所以我无法将其转换为 Rmd,这可能是我的合作者的问题)。

有没有类似于dput()的方法来获取直接格式化为.md的数据帧?

# my data frame
df <- structure(list(year_yyyy = c(2005, 2006, 2007, 2008, 2009), `01` = c(2L, 
2L, 2L, 2L, 2L), `02` = c(2L, 2L, 2L, 2L, 2L), `03` = c(2L, 2L, 
2L, 2L, 3L)), class = "data.frame", row.names = c(NA, -5L)) 

# getting an object I can copy paste to another Rmd document/another session easily
dput(df)

函数 dmd() 的期望输出,这将使我的输出准备好粘贴到 .md 中:

# dmd(df)
# 
# # Which would give
# year_yyyy  |01 |02  |03
# -----------|---|----|---
# 2005       |2  |2   |2    
# 2006       |2  |2   |2   
# 2007       |2  |2   |2    
# 2008       |2  |2   |2    

一旦在 md 中,它看起来像 table:

在此先感谢您的帮助!

knitr 中的

kable() 似乎可以满足您的要求:

knitr::kable(df, format="pipe")


#| year_yyyy| 01| 02| 03|
#|---------:|--:|--:|--:|
#|      2005|  2|  2|  2|
#|      2006|  2|  2|  2|
#|      2007|  2|  2|  2|
#|      2008|  2|  2|  2|
#|      2009|  2|  2|  3|

如果您想获得与示例中完全相同的格式,则可能需要指定 align 参数。