Ranon Kahn Ranon Kahn - 16 days ago 7
R Question

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

As the next step to the example provided in http://rstudio.github.io/DT/010-style.html I wish to highlight a part of a string in a cell based on a filter value as shown in the image below. I am trying to highlight specific motifs in biological sequence data in table format. Given below is the Excel VBA code and a representative image. Is it possible to achieve this in R?

Sub SequencePartColourMacro()
Dim Col, Row, FirstRow, LastRow As Integer, Col As Long

Col = 6
FirstRow = 2
LastRow = ThisWorkbook.Sheets("Sequences").Cells(Rows.Count, "F").End(xlUp).Row

Test1 = "CC"
Test2 = "TT"
Test3 = "GG"

For Row = FirstRow To LastRow
Sequence = ThisWorkbook.Sheets("Sequences").Cells(Row, Col).Value
For x = 1 To Len(Sequence)
SubSequence1 = Mid(Sequence, x, 2)
If SubSequence1 = Test1 Then
ThisWorkbook.Sheets("Sequences").Cells(Row, Col).Characters(x, 2).Font.Color = RGB(0, 0, 255)
ThisWorkbook.Sheets("Sequences").Cells(Row, Col).Characters(x, 2).Font.Bold = True
End If
If SubSequence1 = Test2 Then
ThisWorkbook.Sheets("Sequences").Cells(Row, Col).Characters(x, 2).Font.Color = RGB(0, 102, 0)
ThisWorkbook.Sheets("Sequences").Cells(Row, Col).Characters(x, 2).Font.Bold = True
End If
If SubSequence1 = Test3 Then
ThisWorkbook.Sheets("Sequences").Cells(Row, Col).Characters(x, 2).Font.Color = RGB(255, 153, 0)
ThisWorkbook.Sheets("Sequences").Cells(Row, Col).Characters(x, 2).Font.Bold = True
End If
Next x
Next Row
End Sub


Representative image showing highlighted characters

Answer

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'))

enter image description here

Comments