条件格式化单元格R DataTable

时间:2017-06-05 21:35:18

标签: r datatable

我需要在我的数据表中实现条件格式。请参阅下面的示例。我需要的是突出第三行,#34; PercentDone",基于该数字是否大于第4行和第5行的阈值。

如果数字大于50%,我想将其突出显示为绿色。

如果介于25%和50%之间,我想将其突出显示为黄色。

如果低于25%,我想将其突出显示为红色。

这类似于有人在Excel中使用条件格式进行的操作,我只是不确定如何在R中的数据表中实现它。

在下面的示例中,第1列中的46%应为黄色,第2列中的11%应为红色,第3列中的65%应为绿色。

df = data.frame(
  c(51, 59, '46%', '25%', '50%'),
  c(12, 93, '11%', '25%', '50%'),
  c(40, 22, '65%', '25%', '50%'))

colnames(df) = c('Location1', 'Location2', 'Location3')
rownames(df) = c('Done', 'Need', 'PercentDone', 'Threshold1', 'Threshold2')

DT = datatable(df) %>%
  formatStyle(...)

1 个答案:

答案 0 :(得分:2)

最新回复,但可能对其他人有用,因此我正在发布。
如果转置表格不是问题,则可以尝试以下操作。

决赛桌应该像这样:

enter image description here

DF = data.frame(
 c(51, 59, '46%', '25%', '50%'),
 c(12, 93, '11%', '25%', '50%'),
 c(40, 22, '65%', '25%', '50%'), stringsAsFactors = FALSE )# variables as chr, w/o factor levels)


colnames(DF) = c('Location1', 'Location2', 'Location3')
rownames(DF) = c('Done', 'Need', 'PercentDone', 'Threshold1', 'Threshold2')

head(DF)

仅从百分比中检索数字,将其转换为数字以进行比较:

# Define function for retrieving digits; One-liner courtesy of @stla at GitHub
Numextract <- function(string){ unlist(regmatches(string,gregexpr("[[:digit:]]+\\.*[[:digit:]]*",string)))}

# Apply Numextract to all dataframe; 
# retrieves only digits but still class is chr
DF [,] <- lapply(DF[,], Numextract)

# Convert to numeric to allow for comparison
DF [,] <- lapply(DF[,], as.numeric)

# Transpose dataframe to access the `PercentDone` as a column
DF = t(DF)

考虑从数据框中删除值,并将其作为vars

Threshold1 = 25
Threshold2 = 50

自定义数据表:高亮显示PercentDone

DT::datatable(DF, 
          filter  = "bottom",
          caption = "I am the title",


          # OPTIONS:
          options = list(

            initComplete = JS(
              "function(settings, json) {",
              "$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});",
              "}"),
            columnDefs = list(list(targets = length(colnames(DF)), visible = TRUE)))) %>% 

# Change fontsize of cell values
 formatStyle(columns    = c(1:length(colnames(df))), 
           fontSize   = "85%",
          fontFamily = "Verdana")%>%



 # Format column based on P.Value levels
 formatStyle(fontWeight = 'bold',
          # Format this:
          "PercentDone",

          # Font color
          color = styleInterval(c(0.0), c('black', 'black')),
          backgroundColor = styleInterval(c(Threshold1, Threshold2), 
                                          c('lightgreen', '#f4d35e', "tomato"))) -> fancyTable


# Print customized color-coded datatable:
fancyTable
相关问题