我正在使用kable
,并且要为500个数据集创建表,因此,我试图创建一个脚本并在其上循环。我感到难过的一件事是我使用了group_rows
选项,尽管在数据集之间组的数量会改变。如何设置一个R脚本来考虑这一点。
这是我的脚本,目前在kable
命令内使用普通循环,此循环不起作用...
[数据集grps
是确定组的预定义条件]
对于以下代码,下面的grps
和color
数据集。它们根本没有连接到mtcars
:
grps <-
structure(list(no.cars = c(2,1,2), maincars = c("Mazda",
"Datsun", "Hornet"), start = c(1, 3, 4),
end = c(2L, 3L, 5L)), .Names = c("no.cars", "maincars",
"start", "end"), row.names = c(NA, -3L), class = "data.frame")
color <- structure(list(color=c("#20324C", "#D2A8A4", "#FFC65A")),.Names = c("color"), row.names = c(NA,
-3L), class = "data.frame")
mtcars[1:5,] %>%
knitr::kable(format="html")%>%
kable_styling("striped", full_width = F) %>%
for(g in 1:nrow(grps)){
group_rows(grps$maincars[g], grps$start[g], grps$end[g],label_row_css = paste0("background-color: ",color[g,1],"; color: #F1F1F1;")) %>% .()
} %>% as_image()
因此,它没有创建任何组。我很好奇是否可以尝试其他选择?
谢谢
答案 0 :(得分:0)
考虑非管道解决方案:
sub <- mtcars[1:5,]
sub <- knitr::kable(sub, format="html")
sub <- kable_styling(sub, "striped", full_width = FALSE)
for(g in 1:nrow(grps)){
sub <- group_rows(sub, grps$maincars[g], grps$start[g], grps$end[g],
label_row_css = paste0("background-color: ", color[g,1],
"; color: #F1F1F1;")
)
}
as_image(sub)
或者使用管道,结合用户定义的方法:
run_group_rows <- function(x){
for(g in 1:nrow(grps)){
x <- group_rows(x, grps$maincars[g], grps$start[g], grps$end[g],
label_row_css = paste0("background-color: ", color[g,1],
"; color: #F1F1F1;")
)
}
return(x)
}
mtcars[1:5,] %>%
knitr::kable(format="html")%>%
kable_styling("striped", full_width = FALSE) %>%
run_group_rows() %>%
as_image()