# How to do conditional coloring in dataset using new 12.1 functionality?

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

dataset=ExampleData[{"Dataset","Titanic"}][[;;20]];


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

Dataset[dataset,Background->(If[First@#2>10&&Last@#2=="age"&&#1>30,LightYellow]&)]


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

Dataset[dataset,Background->{{11;;,"age"}->(If[#1>30,LightYellow]&)}]


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

Dataset[dataset,Background->(If[MemberQ[{18,19},First@#2]&&Last@#2=="age"&&#1>30,LightYellow]&)]


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[##]&)]


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[

• 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? – user13892 Apr 30 '20 at 15:39
• 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. – user13892 Apr 30 '20 at 15:47