For the first part of this question consider the following dataset as an example:


Suppose I want to highlight the ages above 30 in the second half of this dataset. I can achieve it using the following command:


But if I try it using the part like syntax I can't get it to work.


Please help me find the shortest syntax to achieve this!

Next, suppose I also want an additional constraint that gender should be female. So the output should be like that from the following command.


For the second part of this question consider the following dataset as an example:

--- I will wait for an answer to the first part because maybe then the second part will follow from the first ---


If the conditions are column independent, perhaps having separately defined function with multiple downvalue patterns would be the shortest syntax:

dataset = ExampleData[{"Dataset","Titanic"}][[;;20]]
f[v_, {p_ /; p > 10, "age", ___}, _] := If[v > 30, LightYellow]
f["male", {p_ /; p > 10, "sex", ___}, _] := LightBlue
Dataset[dataset, Background -> (f[##]&)]

enter image description here

Otherwise, if you're looking to conditionally highlight rows, perhaps use multiple queries like this:

qs = {
   Query[Select[#age > 40 && #sex == "male" &]] -> LightGreen,
   Query[Select[#age < 40 && #sex == "female" &]] -> LightBlue,
   Query[Select[#age > 50 && #sex == "male" &]] -> LightYellow
bg = DeleteDuplicates[
   Join @@ Map[
         Alternatives @@ Normal[dataset[#[[1]]]]] -> #[[2]]] &, qs], 
Dataset[dataset, Background -> bg]

enter image description here

  • $\begingroup$ First of all, thank you for this answer. I really like the Background function being defined using DownValue patterns rather than Pure function which makes it very readable and can be understood by people in Business context. Next, I didn't notice there was a third argument as well, any idea what it contains? Maybe it can be used to handle conditions spanning multiple columns? $\endgroup$ – user13892 Apr 30 '20 at 15:39
  • $\begingroup$ In your answer for multiple column condition, you are selecting the matching rows and then finding their position in the dataset. Is there a way to combine these two operations? I know Cases and Select are related and do the same thing, former works with patterns and the latter works with functions. Is there a similar analogue for Position? Position work on patterns; is there a SelectedPosition function that works on functions? because it could combine these two operations. $\endgroup$ – user13892 Apr 30 '20 at 15:47
  • $\begingroup$ These are good points, I agree there should be a more efficient way to do this, hopefully someone else knows how and will post an answer $\endgroup$ – M.R. Apr 30 '20 at 21:20

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.