# How to apply a function with conditional logic based on a column's value to each row in a dataset?

I'm learning Mathematica Datasets and I need to apply a function to each row in a Dataset the performs some conditional logic. Here is my Dataset:

I'm want to add a column to this Dataset that is the goal differential in favor of Winnipeg so I can't just subtract column 5 from column 3. If Winnipeg is the home team it would be column 5 minus column 3.

I assume Mathematica can do this but all I can find is how to apply simple one line functions to each row in a Dataset.

How can I do this?

• Does the person downvoting this have anything constructive to add? Oct 26, 2021 at 3:43
• Could you please load this dataset or part of it that you have been experimenting with?
– Syed
Oct 26, 2021 at 6:55
• You may want to look at Query.
– Syed
Oct 26, 2021 at 7:13
• Probably the downvoters think the second bullet point of mathematica.stackexchange.com/help/on-topic is self-explanatory. Oct 26, 2021 at 18:15

Since a sample of the data was not provided

ds = Dataset[
{<|"Visitor" -> "Montreal", "G" -> 5, "Home" -> "Winnipeg", "H" -> 1|>,
<|"Visitor" -> "Winnipeg", "G" -> 3, "Home" -> "Montreal", "H" -> 4|>}]

ds[All, <|#, "D" -> If[#Home == "Winnipeg", #H - #G, #G - #H]|> &]


• I think we should downvote this answer because it includes a code example and the question didn't. Seems unfair, and unfairness should be discouraged. ;-P Oct 26, 2021 at 18:14
• @MichaelE2 Thanks for the humor! I took a look at Dean Schulze's profile. He has been a member for 7 years and went silent for 7 years after posting his first question. I'm sure the rules and etiquette have changed a lot since then. Perhaps things were more laid back way back then. Dean, please get familiar with the new world order. Oct 26, 2021 at 18:38
• That works. Thanks. What did you mean that a sample of the data was not provided? I showed the data in the screen shot above. The data was imported from .csv file. My data isn't a list of associations like you showed. Oct 26, 2021 at 22:51
• @DeanSchulze I showed the data in the screen shot above Mathematica is very powerful software, but it does not yet have a function ReadDataFromScreenShotAndConvertToPlainTextCode May be in V 13 they will add this. This function will be very useful to have. Oct 26, 2021 at 23:04
• Nasser - My data is a Dataset imported from csv, not a list of associations like you showed. Maybe there is a way to export a Dataset in the form you used? Oct 27, 2021 at 0:21