這是一個解決方案。要使用它,你有一個載體來定義CSS:
css <- c("#bgred {background-color: #FF0000;}",
"#bgblue {background-color: #0000FF;}")
,寫#...
細胞內:
> data.frame(x=c("A","B"), y=c("red cell #bgred", "blue cell #bgblue"))
x y
1 A red cell #bgred
2 B blue cell #bgblue
然後用我的colortable()
功能主要是從highlightHTML
封裝,從我個人的閃亮的靈感經驗。這裏有一個例子:
library(pander)
library(markdown)
library(stringr)
library(shiny)
# function derived from the highlightHTMLcells() function of the highlightHTML package
colortable <- function(htmltab, css, style="table-condensed table-bordered"){
tmp <- str_split(htmltab, "\n")[[1]]
CSSid <- gsub("\\{.+", "", css)
CSSid <- gsub("^[\\s+]|\\s+$", "", CSSid)
CSSidPaste <- gsub("#", "", CSSid)
CSSid2 <- paste(" ", CSSid, sep = "")
ids <- paste0("<td id='", CSSidPaste, "'")
for (i in 1:length(CSSid)) {
locations <- grep(CSSid[i], tmp)
tmp[locations] <- gsub("<td", ids[i], tmp[locations])
tmp[locations] <- gsub(CSSid2[i], "", tmp[locations],
fixed = TRUE)
}
htmltab <- paste(tmp, collapse="\n")
Encoding(htmltab) <- "UTF-8"
list(
tags$style(type="text/css", paste(css, collapse="\n")),
tags$script(sprintf(
'$("table").addClass("table %s");', style
)),
HTML(htmltab)
)
}
##
runApp(
list(
ui=pageWithSidebar(
headerPanel(""),
sidebarPanel(
),
mainPanel(
uiOutput("htmltable")
)
),
server=function(input,output,session){
output$htmltable <- renderUI({
# define CSS tags
css <- c("#bgred {background-color: #FF0000;}",
"#bgblue {background-color: #0000FF;}")
# example data frame
# add the tag inside the cells
tab <- data.frame(x=c("A","B"), y=c("red cell #bgred", "blue cell #bgblue"))
# generate html table with pander package and markdown package
htmltab <- markdownToHTML(
text=pandoc.table.return(
tab,
style="rmarkdown", split.tables=Inf
),
fragment.only=TRUE
)
colortable(htmltab, css)
})
})
)
我不知道這是否可以結合shinyapp輸出,但你可以嘗試HTML轉換器包。在另一方面,我與hwriter的經歷非常積極。 – rdatasculptor