5
$\begingroup$

With the new Dataset/Background option feature introduced in 12.1, I would like to highlight the rows when either of the two columns has one of the target values in its cell. For example, I have the following data:

data = Transpose@Dataset@AssociationThread[{"a", "b", "c"}, RandomInteger[{1, 10}, {3, 10}]]

Iwould like to highlight those rows in red when either col a or b equals 1 or 10.

enter image description here

I can highlight rows based on one-col value, but don't know how to add the 2nd col to the expression.

Dataset[data, Background -> (Switch[#3[#2[[1]], "a"], 1 | 10, LightRed, _, White] &)]

How can I do that? Thanks!

$\endgroup$
8
$\begingroup$
SeedRandom[77];
data = Transpose@Dataset@AssociationThread[{"a", "b", "c"}, 
          RandomInteger[{1, 10}, {3, 10}]];
     
Dataset[data, 
 Background -> Normal[MapIndexed[#2[[1]] -> 
      If[Or @@ (MatchQ[1 | 10] /@ {#a, #b}), Pink, White] &, data, {1}]]] 

enter image description here

$\endgroup$
3
  • 1
    $\begingroup$ Nice use of MapIndexed. I think you meant to write {#a, #b} instead instead of {#a, #c} $\endgroup$ – theorist May 13 at 9:10
  • 1
    $\begingroup$ Thank you @theorist. I had misread the question. Updated with the correction. $\endgroup$ – kglr May 13 at 9:36
  • 1
    $\begingroup$ Thanks for the answer. I really like the way of using MapIndexed and Or. $\endgroup$ – Bemtevi77 May 13 at 14:29
6
$\begingroup$
data = Transpose@
  Dataset@AssociationThread[{"a", "b", "c"}, 
    RandomInteger[{1, 10}, {3, 10}]]

rowcolors = 
 If[MemberQ[{1, 10}, #[[1]]] || MemberQ[{1, 10}, #[[2]]], LightRed, White] & /@ Normal[data];

Dataset[data, Background -> {rowcolors}]

enter image description here

Alternatively,

rowcolors = 
 Table[If[MemberQ[{1, 10}, data[n, "a"]] || 
    MemberQ[{1, 10}, data[n, "b"]], LightRed, White], {n, Length[data]}]
$\endgroup$
1
  • $\begingroup$ Thanks for the answer! I wonder would it be possible to implement via the Pattern Matching? Thanks again. $\endgroup$ – Bemtevi77 May 13 at 7:36
3
$\begingroup$

Given:

SeedRandom[3]
data =
  RandomInteger[{1,10},{10, 3}] //
  Query[Dataset, AssociationThread[{"a", "b", "c"}, #]&]

and a helper function:

color = Replace @ {KeyValuePattern["a"|"b" -> 1|10] -> LightRed, _ -> White};

then we could write:

Dataset[data, Background -> Normal@data[{All}, color]]

or

Dataset[data, Background -> (color[Normal@#3[#2[[1]]]]&)]

dataset with coloured rows

$\endgroup$
1
  • $\begingroup$ This is also very nice solution. I have never learned KeyValuePattern before your answer. Thanks! $\endgroup$ – Bemtevi77 May 14 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.