2017-03-03 71 views
1

我試圖根據上表中的值格式化DT。 例如,我想顯示 增加,減少或保持不變。 我可以用kable來做到這一點,但 無法進入下一步,我想要將單元格鎖住並在另一個DT中顯示與該值相關的所有數據 。根據不同數據集中的值格式化閃亮數據表(DT)的顏色

library(shiny) 
library(DT) 
library(dplyr) 
ui <- fluidPage(
    mainPanel(
     dataTableOutput("iris_head") 
) 
) 

server <- function(input, output) { 

    #df_data <- iris 

    df_data <- head(iris[-5]) 

    # Just a dataset describing if iris has changed over a month 
    # If reference data is of the same size as the original data (df_data). 
    # If reference data is negative I want the cell in the df_data to be green; 
    # If zero blue and if positive then green. 
    # I can make changes with ranges within the current range, can we get the color encoding from another table? 
    # set the seed 
    set.seed(42) 
    reference_df <- (sapply(df_data, function(x) jitter(x, amount = 2)) - df_data) %>% 
    round(. , digits = 0) 

    print(reference_df) 


    output$iris_head <- renderDataTable(datatable(df_data, selection = "single")%>% 
             formatStyle('Sepal.Width', 
                color = styleInterval(c(3.4, 3.8), c('green', 'blue', 'red')), 
                backgroundColor = styleInterval(3.4, c('gray', 'yellow'))) %>% 
             formatString('Sepal.Width', suffix = '<font color="red">&uArr; </font>')) 


} 

shinyApp(ui = ui, server = server) 

在這種情況下的reference_df是:

Sepal.Length Sepal.Width Petal.Length Petal.Width 
     2   1   2   0 
     2   -1   -1   0 
     -1   1   0   2 
     1   1   2   -1 
     1   0   2   2 
     0   1   -2   2 

所需的輸出示於圖中,其中我還想要的顏色的文本,如果可能的話,根據在reference_df值的背景。

enter image description here

回答

3

對於文本顏色的部分,你可以用formatStyle做,但你需要cbinddf_datareference_df,然後把它傳遞給datatable,改變1〜4列的基於價值的風格列5到8:

datatable(cbind(df_data,reference_df), selection = "single", 
               options=list(columnDefs = list(list(visible=FALSE, targets=c(5:8)))))%>% 
             formatStyle(1:4, valueColumns=5:8, 
                color = JS("value < 0 ? 'red' : value > 0 ? 'green' : 'blue'")) 

columnDefs部分隱藏了最後4列。

不能formatString基於值,所以如果你要添加的箭頭,你可以修改df_data它傳遞給datatable之前添加顏色和箭頭:

for(col in 1:dim(df_data)[2]){ 
    df_data[col] <- mapply(function(i,j){ 
     ifelse(i > 0, paste0("<span style='color:red'>",j,"<font>&uArr; </font></span>"), 
      ifelse(i<0, paste0("<span style='color:green'>",j,"<font>&dArr; </font></span>"), 
        paste0("<span style='color:blue'>",j,"<font>&hArr; </font></span>"))) 
    },reference_df[col],df_data[col]) 
    } 

    output$iris_head <- renderDataTable(
    datatable(df_data, selection = "single",escape = F) 
    ) 

此遍歷的值df_data並根據reference_df的值更改它們。您需要escape=F作爲datatable調用中的一個參數來防止HTML轉義。

如果您想爲背景着色等,您可以在span標記中添加更多CSS樣式。

+0

謝謝!對於一個很好解釋的答案。奇怪的是,有人在沒有評論的情況下低估了這個問題,考慮到它得到了這樣一個好的答案。 – discipulus