Message Boards Message Boards

0
|
2296 Views
|
4 Replies
|
2 Total Likes
View groups...
Share
Share this post:

How to calculate and store values off each row of an array?

Posted 2 years ago

Hi, this is probably a very simple question, so apologies in advance. I need to run a calculation off each row of an array (possibly 100k rows) and then store the value of each row (which will be summed and averaged afterward by one of the column values.)

Array structure example:
enter image description here
An example of a simple calculation:

calc = Do[data[[1, 1]]*data[[1, 2]] + data[[1, 3]], ?? ]

The output I'm looking for in this example would be the calculate 7 times 4+3 and then store the value being 31, then calculate 6 times 9+4 and store the value 58, etc. Then I need to sum these stored values up by Group1, Group2, etc..

Thanks in advance.

POSTED BY: Oliver Blombery
4 Replies
Posted 2 years ago
data = {{7, 4, 3}, {6, 9, 4}, {8, 7, 7}, {6, 9,  6}}; 

The Do[ ] function does not produce any results that you could save, you have to use Table[] instead of Do[] , or AppendTo[] inside the Do

res = Table[data[[i, 1]]*data[[i, 2]] + data[[i, 3]], {i, 1, Length@da}];
{data // MatrixForm , res // MatrixForm}
POSTED BY: Legibus Motus
Posted 2 years ago

Here's one way.

Start by applying your arithmetic function to each row while retaining the group label:

{#[[1]], #[[2]]*#[[3]] + #[[4]]} & /@ data
(* {{"g1", 31}, {"g1", 58}, {"g1", 63}, {"g2", 60}, {"g2", 32}, {"g2", 65}, {"g3", 27}, {"g3", 30}, {"g3", 30}} *)

Now group by the first item, the label:

GroupBy[{#[[1]], #[[2]]*#[[3]] + #[[4]]} & /@ data, First -> Rest]
(* <|"g1" -> {{31}, {58}, {63}}, "g2" -> {{60}, {32}, {65}}, "g3" -> {{27}, {30}, {30}}|> *)

Now tack on a sum calculation with Total:

Total[#, 2] & /@ GroupBy[{#[[1]], #[[2]]*#[[3]] + #[[4]]} & /@ data, First -> Rest]
(* <|"g1" -> 152, "g2" -> 157, "g3" -> 87|> *)
POSTED BY: Eric Rimbey

Thanks very much, exactly what I needed!

POSTED BY: Oliver Blombery
Posted 2 years ago

GroupBy can take a third argument which is a reducer function that is applied to the grouped values. Eric's answer can be written as

GroupBy[{#[[1]], #[[2]]*#[[3]] + #[[4]]} & /@ data, First -> Rest, Total/*First]
POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract