Highlight part of a string in a cell content based on a filter value

こ雲淡風輕ζ 提交于 2019-12-06 08:48:28

This is a little verbose, but so is VBA in general:

library(DT)
set.seed(1986)
x <- vector()
# create fake dna or rna sequence (it's been a while since I took bio)
for (i in 1:10) {
  x[i] <- paste0(sample(c("A","G","T","C"),10,replace=TRUE), collapse="")
}

dim(x) <- c(5,2)

datatable(x, options = list(rowCallback=JS(
  "function(row,data) {
    data[0]=data[0].replace('CC','<span style=\"color:red\">CC</span>');
    data[0]=data[0].replace('TT','<span style=\"color:blue\">TT</span>');
    data[0]=data[0].replace('GG','<span style=\"color:green\">GG</span>');
    data[1]=data[1].replace('CC','<span style=\"color:red\">CC</span>');
    data[1]=data[1].replace('TT','<span style=\"color:blue\">TT</span>');
    data[1]=data[1].replace('GG','<span style=\"color:green\">GG</span>');
    $('td:eq(0)', row).html(data[0]);
    $('td:eq(1)', row).html(data[1]);
  }"
  ), dom = 't'))

Little tweaking of @Carl's code results in identifying and highlighting all occurrences of a chosen string. May be useful to someone like me.

library(DT)
set.seed(1986)
x <- vector()
 create fake dna or rna sequence (it's been a while since I took bio)
for (i in 1:10) {
 x[i] <- paste0(sample(c("A","G","T","C"),25,replace=TRUE), collapse="")
}
dim(x) <- c(5,2)

datatable(x, options = list(rowCallback=JS(
  "function(row,data) {
  data[0] = data[0]  .replace(/GA/g,'<span style=\"color:red\">GA</span>');
  data[0] = data[0]  .replace(/TT/g,'<span style=\"color:blue\">TT</span>');
  data[0] = data[0]  .replace(/TC/g,'<span style=\"color:green\">TC</span>');
  data[1] = data[1]  .replace(/GA/g,'<span style=\"color:red\">GA</span>');
  data[1] = data[1]  .replace(/TT/g,'<span style=\"color:blue\">TT</span>');
  data[1] = data[1]  .replace(/TC/g,'<span style=\"color:green\">TC</span>');
  $('td:eq(0)', row).html(data[0]  );
  $('td:eq(1)', row).html(data[1]  );
  }"
  ), dom = 't'))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!