问题
Is it possible to render a list of data frames in a markdown document as individual tables?
Example
Given the code chunk
```{r listOfDf}
library(knitr)
df <- data.frame(a=rnorm(10),b=rnorm(10),c=c(rep("a",5), rep("b",5)))
l_df <- split(df, df$c)
kable(l_df)
```
This outputs

But I would like something closer to that given in the R console:
> l_df
$a
a b c
1 1.2869909 -0.3117932 a
2 1.4621792 1.2826924 a
3 -0.4274641 0.3335532 a
4 0.7882973 -1.1966702 a
5 -1.2086910 0.1549691 a
$b
a b c
6 -0.9460508 1.4679430 b
7 0.6580554 0.5806850 b
8 -0.7103335 2.6036176 b
9 -2.0110167 2.0488055 b
10 0.7691045 0.3652907 b
But that is also rendered as a table(s) (hence the use of kable()
)
I've tried a loop*
for(i in 1:length(l_df)){
kable(l_df[i])
}
but that doesn't work either (*but it does work for graphs)
回答1:
The pander
package was created to transform almost any R objects into markdown. E.g.:
> pander(l_df)
* **a**:
-------------------------
a b c
---------- ---------- ---
0.5853656 1.3888279 a
-0.6172632 -0.5179708 a
-0.3321862 -0.2400778 a
-0.6503349 0.9474224 a
0.9476588 0.2288404 a
-------------------------
* **b**:
-------------------------------------
a b c
-------- ------------ ----------- ---
**6** -0.637650387 0.26547037 b
**7** 0.233576764 -0.47811415 b
**8** -0.283486652 0.61113065 b
**9** -0.794994493 -0.08609191 b
**10** -0.004526202 0.36841059 b
-------------------------------------
<!-- end of list -->
回答2:
I use this function with {r results='asis'}
affiche_multi_df <- function(b){
for ( i in seq_along(b)){
cat(glue::glue("### {names(b)[i]} \n\n"))
b[[i]] %>%
DT::datatable() %>%
htmltools::tagList() %>%
print()
}}
like this
```{r results='asis'}
list(a=iris,b=iris,c=iris) %>% affiche_multi_df()
```
来源:https://stackoverflow.com/questions/31317373/r-rmarkdown-render-list-of-dataframes