add row based on column calculations

8 views
Skip to first unread message

rebich01

unread,
Feb 18, 2010, 12:44:02 PM2/18/10
to Ruby Reports
Hi.

I'm trying to add a row to the bottom of my table where each cell is
the average of two cells from other rows (in the same column). It's
simple enough to add columns based on earlier columns, but it's not
very apparent how to do the equivalent with rows.

| A | B | C |
A' | 10 | 8 | 4 |
B' | 12 | 4 | 4 |
C' | 6 | 6 | 2 |

I want to add a row D' that, for each column, is the average of B' +
C'. What's the best way to approach this?

Thanks in advance.

Lucas Nunes

unread,
Feb 18, 2010, 1:39:53 PM2/18/10
to ruby-r...@googlegroups.com
2010/2/18 rebich01 <rebi...@gmail.com>
Hi.

[...]
 
I want to add a row D' that, for each column, is the average of B' +
C'.  What's the best way to approach this?

Thanks in advance.

Hi!

Based on what you said, I'd do something like this:

table << table[-2].zip(table[-1]).map{|a,b| a+b}

Tell us if it worked. ;)

Cheers!
--
Lucas Dutra Nunes

Lucas Nunes

unread,
Feb 18, 2010, 1:44:13 PM2/18/10
to ruby-r...@googlegroups.com
Ops! I forgot the average! There you go:

table << table[-2].zip(table[-1]).map{|a,b| (a+b)/2}

If you want more precision, comvert the sum result to float:

table << table[-2].zip(table[-1]).map{|a,b| (a+b).to_f/2}
Reply all
Reply to author
Forward
0 new messages