我有一个R Markdown / knittr文档,可以生成成对的图表和表格。对的数量是可变的,所以我在循环内创建它们。 我希望结果在输出中交错:表1,图1,表2,图2 ......
在下面的示例中,所有表格首先位于文档的顶部。我尝试了各种各样的排列
编辑:我找到了一个解决方案并将其发布在下面。现在我正在寻找一个与我在custom R Markdown plot size within loop收到的高度可变高度建议兼容的建议吗?
```{r cars, echo=FALSE}
library(ggplot2)
library(knitr)
carb.possibilities <- sort(unique(as.character(mtcars$carb)))
filtereds <- lapply(carb.possibilities, function(carb.ct) {
return(mtcars[ mtcars$carb == carb.ct , ])
})
carb.possibilities <- paste(carb.possibilities, ' Carburetors', sep = '')
names(filtereds) <- carb.possibilities
lapply(carb.possibilities, function(one.possibility) {
current.possibility <- filtereds[[one.possibility]]
print(kable(current.possibility))
ggplot(current.possibility, aes(factor(gear), mpg)) +
coord_flip() +
labs(x = "Gears", title = one.possibility) +
geom_point(position=position_jitter( width = 0.1, height = 0.1) )
})
```
答案 0 :(得分:1)
使用asis,将表格和绘图包装在print()中并捕捉换行符解决了交错问题。我还没想到如何将它与custom R Markdown plot size within loop
中的可变高度图结合起来请参阅https://github.com/yihui/knitr/issues/886
```{r cars, echo=FALSE, results='asis'}
library(ggplot2)
library(knitr)
carb.possibilities <- sort(unique(as.character(mtcars$carb)))
filtereds <- lapply(carb.possibilities, function(carb.ct) {
return(mtcars[ mtcars$carb == carb.ct , ])
})
carb.possibilities <- paste(carb.possibilities, ' Carburetors', sep = '')
names(filtereds) <- carb.possibilities
for(one.possibility in carb.possibilities){
current.possibility <- filtereds[[one.possibility]]
my.ggplot <- ggplot(current.possibility, aes(factor(gear), mpg)) +
coord_flip() +
labs(x = "Gears", title = one.possibility) +
geom_point(position=position_jitter( width = 0.1, height = 0.1) )
print(kable(current.possibility))
cat('\n')
print(my.ggplot)
}
```